import { useColor } from "@/hooks/useColor";
import React, { useEffect } from "react";
import { Pressable } from "react-native";
import Animated, {
  interpolate,
  interpolateColor,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated";

export default function CustomSwitch({
  active,
  onPress,
}: {
  active: boolean;
  onPress: () => void;
}) {
  const isOn = useSharedValue(active);

  useEffect(() => {
    isOn.value = active;
  }, [active]);

  const handlePress = () => {
    isOn.value = !isOn.value;
    onPress();
  };

  const { primary } = useColor();
  const height = useSharedValue(0);
  const width = useSharedValue(0);

  const trackAnimatedStyle = useAnimatedStyle(() => {
    const progress = isOn.value ? 1 : 0;
    const color = interpolateColor(progress, [0, 1], ["#e2e8f0", primary.base]);
    const colorValue = withTiming(color, { duration: 400 });

    return {
      backgroundColor: colorValue,
      borderRadius: height.value / 2,
    };
  });

  const thumbAnimatedStyle = useAnimatedStyle(() => {
    const moveValue = interpolate(
      Number(isOn.value),
      [0, 1],
      [0, width.value - height.value]
    );
    const translateValue = withTiming(moveValue, { duration: 400 });

    return {
      transform: [{ translateX: translateValue }],
      borderRadius: height.value / 2,
    };
  });

  return (
    <Pressable onPress={handlePress}>
      <Animated.View
        onLayout={(e) => {
          height.value = e.nativeEvent.layout.height;
          width.value = e.nativeEvent.layout.width;
        }}
        style={[trackAnimatedStyle]}
        className={"w-[58px] h-8 p-1 items-start"}
      >
        <Animated.View
          style={[thumbAnimatedStyle]}
          className={"h-full aspect-[1] bg-white"}
        ></Animated.View>
      </Animated.View>
    </Pressable>
  );
}
