import { useRef, useEffect } from "react";
import { Modal, Pressable, Animated, useWindowDimensions } from "react-native";
import { FlashList } from "@shopify/flash-list";
import { useThemeStore } from "../stores/ThemeStore";
import { Theme } from "../Themes";

export type ScrollableDropdownProps<T> = {
  visible: boolean;
  onClose: () => void;
  position: {
    top?: number;
    bottom?: number;
    left: number;
    width: number;
  };
  data: T[];
  keyExtractor: (item: T) => string;
  renderItem: (item: T, theme: Theme) => React.ReactNode;
  onSelect: (item: T) => void;
  height?: number;
  heightRatio?: number; // Alternative: fraction of screen height (0-1)
  initialScrollIndex?: number;
  // Infinite scroll (optional)
  onEndReached?: () => void;
  onStartReached?: () => void;
};

export const ScrollableDropdown = <T,>({
  visible,
  onClose,
  position,
  data,
  keyExtractor,
  renderItem,
  onSelect,
  height = 200,
  heightRatio,
  initialScrollIndex = 0,
  onEndReached,
  onStartReached,
}: ScrollableDropdownProps<T>) => {
  const { theme } = useThemeStore();
  const { height: screenHeight } = useWindowDimensions();
  const heightAnim = useRef(new Animated.Value(0)).current;
  const listRef = useRef<React.ComponentRef<typeof FlashList<T>>>(null);

  // Calculate actual height: use heightRatio if provided, otherwise fall back to height
  const actualHeight = heightRatio ? screenHeight * heightRatio : height;
  // Calculate top position: use top if provided, otherwise calculate from bottom
  const topValue =
    position.top ?? screenHeight - actualHeight - (position.bottom ?? 0);

  useEffect(() => {
    if (visible) {
      Animated.timing(heightAnim, {
        toValue: actualHeight,
        duration: 200,
        useNativeDriver: false,
      }).start();
    } else {
      heightAnim.setValue(0);
    }
  }, [visible, heightAnim, actualHeight]);

  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={onClose}
    >
      <Pressable className="flex-1 rounded-lg" onPress={onClose}>
        <Animated.View
          className="absolute overflow-hidden"
          style={{
            top: topValue,
            left: position.left,
            width: position.width,
            height: heightAnim,
            backgroundColor: theme.primeBg,
            borderWidth: 2,
            borderColor: theme.borderPrimary,
            borderRadius: 8,
          }}
        >
          <FlashList
            className="w-full"
            style={{ borderRadius: 8 }}
            ref={listRef}
            keyExtractor={keyExtractor}
            data={data}
            initialScrollIndex={initialScrollIndex}
            onEndReachedThreshold={0.5}
            onEndReached={onEndReached}
            onStartReachedThreshold={0.5}
            onStartReached={onStartReached}
            renderItem={({ item }) => (
              <Pressable onPress={() => onSelect(item)}>
                {renderItem(item, theme)}
              </Pressable>
            )}
          />
        </Animated.View>
      </Pressable>
    </Modal>
  );
};
