import React, {useEffect} from 'react';
import {GestureResponderEvent, Pressable, PressableProps} from 'react-native';
import Animated, {
  interpolate,
  interpolateColor,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import {useTheme} from '@shared/theme';

import {CIRCLE_X_TRANSLATION, styles} from './styles';

export interface ToggleProps extends PressableProps {
  value: boolean;
  onToggle: (newValue: boolean) => void;
}

export function Toggle({
  value,
  onToggle,
  disabled,
  onPress,
  ...props
}: ToggleProps) {
  const {theme} = useTheme();
  const sharedValue = useSharedValue(0);

  const onTogglePress = (e: GestureResponderEvent) => {
    onToggle(!value);
    onPress?.(e);
  };

  const containerAnimatedStyles = useAnimatedStyle(() => ({
    backgroundColor: disabled
      ? sharedValue.value
        ? theme.action.background.brand.selected
        : theme.button.background.primary.disabled
      : interpolateColor(
          sharedValue.value,
          [0, 1],
          [
            theme.button.background.primary.disabled,
            theme.button.background.primary.default,
          ],
        ),
  }));

  const circleAnimatedStyles = useAnimatedStyle(() => ({
    transform: [
      {
        translateX: interpolate(
          sharedValue.value,
          [0, 1],
          [0, CIRCLE_X_TRANSLATION],
        ),
      },
    ],
  }));

  useEffect(() => {
    sharedValue.value = withTiming(value ? 1 : 0, {duration: 200});
  }, [sharedValue, value]);

  return (
    <Pressable onPress={onTogglePress} disabled={disabled} {...props}>
      <Animated.View style={[styles.container, containerAnimatedStyles]}>
        <Animated.View
          style={[
            styles.circle,
            {
              backgroundColor: theme.button.background.secondary.default,
            },
            circleAnimatedStyles,
          ]}
        />
      </Animated.View>
    </Pressable>
  );
}
