import React from 'react';
import { View, TouchableOpacity } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
  interpolateColor
} from 'react-native-reanimated';
import { FontAwesome } from '@expo/vector-icons';

import { Colors } from 'src/theme';

const StarRating = ({
  rating,
  onRatingChange
}: {
  rating: number;
  onRatingChange: (s: number) => void;
}) => {
  const animatedValues = Array(5)
    .fill(0)
    .map(() => useSharedValue(1));
  const colorValues = Array(5)
    .fill(0)
    .map(() => useSharedValue(0));

  const handlePress = (star: number) => {
    onRatingChange(star);
    animateStar(star);
  };

  const animateStar = (star: number) => {
    animatedValues[star - 1].value = withTiming(1.3, { duration: 150 }, () => {
      animatedValues[star - 1].value = withTiming(1, { duration: 150 });
    });
    colorValues[star - 1].value = withTiming(1, { duration: 150 }, () => {
      colorValues[star - 1].value = withTiming(0, { duration: 150 });
    });
  };

  return (
    <View style={{ flexDirection: 'row', justifyContent: 'center', gap: 5 }}>
      {[1, 2, 3, 4, 5].map((star, index) => {
        const animatedStyle = useAnimatedStyle(() => ({
          transform: [{ scale: animatedValues[index].value }]
        }));

        const animatedColor = useAnimatedStyle(() => {
          const color = interpolateColor(
            colorValues[index].value,
            [0, 1],
            [Colors.DARK_BLUE, Colors.LIGHT_GRAY]
          );
          return { color };
        });

        return (
          <TouchableOpacity key={star} onPress={() => handlePress(star)}>
            <Animated.View style={animatedStyle}>
              <Animated.Text style={animatedColor}>
                <FontAwesome name={rating >= star ? 'star' : 'star-o'} size={22} />
              </Animated.Text>
            </Animated.View>
          </TouchableOpacity>
        );
      })}
    </View>
  );
};

export default StarRating;
