import React, { useCallback, useState } from 'react'
import { StyleProp, View, ViewStyle } from 'react-native'

/**
 * Positions children so that the center of the element is at desiredCenterPosition (0..1), but clamps it when it would overflow
 *  @param desiredCenterPosition the desired position of the center of the child element
 */

export const ConstrainedSlider: React.FC<{
  desiredCenterPosition: number
  style?: StyleProp<ViewStyle>
}> = ({ desiredCenterPosition, style, children }) => {
  const [containerSize, setContainerSize] = useState<number | null>(null)
  const onContainerLayout = useCallback((event) => {
    setContainerSize(event.nativeEvent.layout.width)
  }, [])

  const [childSize, setChildSize] = useState<number | null>(null)
  const onChildLayout = useCallback((event) => {
    setChildSize(event.nativeEvent.layout.width)
  }, [])

  const position =
    containerSize !== null && childSize !== null
      ? Math.floor(
          Math.min(
            containerSize - childSize,
            Math.max(0, desiredCenterPosition * containerSize - childSize / 2)
          )
        )
      : 0

  return (
    <View
      style={[
        {
          flexDirection: 'row',
        },
        style,
      ]}
      onLayout={onContainerLayout}
    >
      <View
        style={{
          position: 'absolute',
          left: position,
          opacity: containerSize && childSize ? 1 : 0,
        }}
        onLayout={onChildLayout}
      >
        {children}
      </View>
    </View>
  )
}
