import {
  View,
  Animated,
  Text,
  Dimensions,
  Image,
  NativeSyntheticEvent,
  NativeScrollEvent,
} from "react-native";
import { PlaceInfoEntity } from "../../../place/domain/entities/place_info_entity";
import { useRef } from "react";
import { CarousselTile } from "./caroussel_tile";
import { router } from "expo-router";
import { BLANK_ITEM_WIDTH, ITEM_WIDTH } from "../../const/caroussel";

interface CarousselProps {
  data: PlaceInfoEntity[];
  onPress?: (id: number) => void;
  onIndexChange?: (index: number) => void;
}

export const Caroussel = ({ data, onPress, onIndexChange }: CarousselProps) => {
  const scrollX = useRef(new Animated.Value(0)).current;
  const finalData = [
    {
      id: -1,
      name: "empty-left",
    },
    ...data,
    {
      id: -2,
      name: "empty-right",
    },
  ];

  scrollX.addListener(({ value }) => {
    const index = Math.round(value / ITEM_WIDTH);
    if (index < 0 || index >= data.length) {
      return;
    }
    onIndexChange && onIndexChange(index);
  });
  return (
      <Animated.FlatList
        data={finalData}
        keyExtractor={(item) => item.id.toString()}
        horizontal
        showsHorizontalScrollIndicator={false}
        decelerationRate={0}
        initialNumToRender={1}
        bounces={false}
        snapToInterval={ITEM_WIDTH}
        onScroll={Animated.event(
          [{ nativeEvent: { contentOffset: { x: scrollX } } }],
          {
            useNativeDriver: true,
          }
        )}
        renderItem={({ item, index }) => {
          if (item.id === -1 || item.id === -2) {
            return <View style={{ width: BLANK_ITEM_WIDTH }} />;
          }
          const inputRange = [
            (index - 2) * ITEM_WIDTH,
            (index - 1) * ITEM_WIDTH,
            index * ITEM_WIDTH,
          ];

          const translateY = scrollX.interpolate({
            inputRange,
            outputRange: [100, 0, 100],
          });

          const opacity = scrollX.interpolate({
            inputRange,
            outputRange: [0.6, 1, 0.6],
          });
          const scale = scrollX.interpolate({
            inputRange,
            outputRange: [0.8, 1, 0.8],
          });
          return (
            <CarousselTile
              opacity={opacity}
              scale={scale}
              translateY={translateY}
              item={item}
              onPress={() => {
                if (item.id !== -1 && item.id !== -2) {
                  onPress && onPress(item.id);
                }
              }}
            />
          );
        }}
      />
  );
};
