import { Check } from 'lucide-react-native';
import { RefObject, useCallback, useState } from 'react';
import { Modal, Pressable, StyleSheet, View } from 'react-native';
import { Text } from './Text';
import { font, radius, shadows, spacing, useColors } from './styles';

type DropdownOption = { label: string; value: string };

type DropdownProps = {
  triggerRef: RefObject<View | null>;
  visible: boolean;
  onClose: () => void;
  options: DropdownOption[];
  selected?: string;
  onSelect: (value: string) => void;
};

type Position = { top: number; right: number };

export function Dropdown({
  triggerRef,
  visible,
  onClose,
  options,
  selected,
  onSelect,
}: DropdownProps) {
  const c = useColors();
  const [position, setPosition] = useState<Position | null>(null);

  const measureAndShow = useCallback(() => {
    triggerRef.current?.measureInWindow((x, y, width, height) => {
      setPosition({ top: y + height + 4, right: 24 });
    });
  }, [triggerRef]);

  if (!visible) return null;

  return (
    <Modal visible transparent animationType="fade" onShow={measureAndShow}>
      <Pressable style={styles.backdrop} onPress={onClose}>
        {position && (
          <View
            style={[
              styles.menu,
              shadows.md,
              {
                backgroundColor: c.surface,
                borderColor: c.border,
                top: position.top,
                right: position.right,
              },
            ]}
          >
            {options.map((opt, i) => {
              const isSelected = opt.value === selected;
              const isLast = i === options.length - 1;
              return (
                <Pressable
                  key={opt.value}
                  style={({ pressed }) => [
                    styles.option,
                    !isLast && {
                      borderBottomWidth: StyleSheet.hairlineWidth,
                      borderBottomColor: c.borderSubtle,
                    },
                    pressed && { backgroundColor: c.tagBg },
                  ]}
                  onPress={() => {
                    onSelect(opt.value);
                    onClose();
                  }}
                >
                  <Text style={[styles.optionText, { color: isSelected ? c.accent : c.text }]}>
                    {opt.label}
                  </Text>
                  {isSelected && (
                    <Check size={16} color={c.accent} strokeWidth={2.5} style={styles.checkmark} />
                  )}
                </Pressable>
              );
            })}
          </View>
        )}
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: {
    flex: 1,
  },
  menu: {
    position: 'absolute',
    minWidth: 160,
    borderRadius: radius.md,
    borderWidth: 1,
    overflow: 'hidden',
  },
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  optionText: {
    fontSize: font.md,
    fontWeight: '500',
  },
  checkmark: {
    marginLeft: spacing.sm,
  },
});
