import React, { useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  FlatList,
} from "react-native";
import { Feather } from "@expo/vector-icons";

type Props = {
  options: string[];
  selected: string;
  onSelect: (val: string) => void;
  placeholder?: string;
};

const FilterDropdown = ({
  options,
  selected,
  onSelect,
  placeholder,
}: Props) => {
  const [open, setOpen] = useState(false);

  return (
    <View style={styles.dropdownContainer}>
      <TouchableOpacity
        style={styles.dropdownHeader}
        onPress={() => setOpen(!open)}
      >
        <Text style={styles.dropdownText}>
          {selected || placeholder || "Chọn"}
        </Text>
        <Feather
          name={open ? "chevron-up" : "chevron-down"}
          size={16}
          color="#333"
        />
      </TouchableOpacity>

      {open && (
        <View style={styles.dropdownList}>
          <FlatList
            data={options}
            keyExtractor={(item) => item}
            renderItem={({ item }) => (
              <TouchableOpacity
                style={styles.option}
                onPress={() => {
                  onSelect(item);
                  setOpen(false);
                }}
              >
                <Text style={styles.optionText}>{item}</Text>
              </TouchableOpacity>
            )}
          />
        </View>
      )}
    </View>
  );
};

export default FilterDropdown;

const styles = StyleSheet.create({
  dropdownContainer: {
    width: 150,
    marginTop: 10,
    marginBottom: 10,
    position: "relative",
    marginRight: 10,
  },
  dropdownHeader: {
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 6,
    paddingHorizontal: 10,
    paddingVertical: 8,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    backgroundColor: "#fff",
  },
  dropdownText: {
    fontSize: 14,
  },
  dropdownList: {
    position: "absolute",
    top: 37,
    width: "100%",
    borderWidth: 1,
    borderColor: "#ccc",
    borderTopWidth: 0,
    borderRadius: 6,
    overflow: "hidden",
    maxHeight: 150,
    backgroundColor: "#fff",
    zIndex: 1000,
  },
  option: {
    padding: 10,
  },
  optionText: {
    fontSize: 14,
  },
});
