import React, { useState, useRef } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  FlatList,
  Modal,
  Animated,
  StyleSheet,
  SafeAreaView,
  StatusBar,
  ViewStyle,
  TextStyle,
  Platform,
  Dimensions,
  Easing,
} from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
import countries from "./assets/countries.json";

// Define types for props and state
type Country = {
  name: string;
  code: string;
  iso: string;
  flag: string;
};

type CountryPickerPhoneInputProps = {
  defaultCountryCode?: string;
  customCountries?: Country[];
  onCountrySelect?: (country: Country) => void;
  onPhoneNumberChange?: (phoneNumber: string) => void;
  onFormattedPhoneNumberChange?: (formattedPhoneNumber: string) => void;
  containerStyle?: ViewStyle;
  flagContainerStyle?: ViewStyle;
  countryCodeStyle?: TextStyle;
  phoneInputStyle?: TextStyle;
  placeholder?: string;
  chevronColor?: string;
  chevronSize?: number;
  placeholderTextColor?: string;
  closeButtonStyle?: ViewStyle;
  closeIconColor?: string;
  closeIconSize?: number;
  searchContainerStyle?: ViewStyle;
  searchIconStyle?: ViewStyle;
  searchIconColor?: string;
  searchIconSize?: number;
  searchInputStyle?: TextStyle;
  countryItemStyle?: ViewStyle;
  countryItemFlagStyle?: TextStyle;
  countryItemNameStyle?: TextStyle;
  countryItemCodeStyle?: TextStyle;
};

const CountryPickerPhoneInput: React.FC<CountryPickerPhoneInputProps> = ({
  defaultCountryCode = "PK",
  customCountries = countries,
  onCountrySelect,
  onPhoneNumberChange,
  onFormattedPhoneNumberChange,
  containerStyle,
  flagContainerStyle,
  countryCodeStyle,
  phoneInputStyle,
  placeholder,
  placeholderTextColor,
  chevronColor,
  chevronSize,
  closeButtonStyle,
  closeIconColor,
  closeIconSize,
  searchContainerStyle,
  searchIconStyle,
  searchIconColor,
  searchIconSize,
  searchInputStyle,
  countryItemStyle,
  countryItemFlagStyle,
  countryItemNameStyle,
  countryItemCodeStyle,
}) => {
  const [selectedCountry, setSelectedCountry] = useState<Country>(
    customCountries.find(
      (country) =>
        country.code === defaultCountryCode ||
        country.iso === defaultCountryCode
    ) || customCountries[0]
  );
  const [phoneNumber, setPhoneNumber] = useState<string>("");
  const [isModalVisible, setModalVisible] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>("");
  const screenHeight = Dimensions.get("window").height;
  // const slideAnim = useRef(new Animated.Value(screenHeight)).current; // Initial off-screen position
  const slideAnim = useRef(new Animated.Value(0)).current;

  const filteredCountries = customCountries.filter((country) =>
    country.name.toLowerCase().includes(searchText.toLowerCase())
  );

  const openModal = () => {
    setModalVisible(true);
    Animated.timing(slideAnim, {
      toValue: 1,
      duration: 300,
      useNativeDriver: true,
    }).start();
  };

  const closeModal = () => {
    Animated.timing(slideAnim, {
      toValue: 0, // Move back to the bottom
      duration: 300,
      easing: Easing.ease,
      useNativeDriver: true,
    }).start(() => {
      // Hide modal after animation completes
      setModalVisible(false);
      setSearchText("");
    });
  };
  const selectCountry = (country: Country) => {
    setSelectedCountry(country);
    closeModal();
    onCountrySelect?.(country);
  };

  const handlePhoneNumberChange = (number: string) => {
    setPhoneNumber(number);
    onPhoneNumberChange?.(number);
    onFormattedPhoneNumberChange?.(`${selectedCountry?.code}${number}`);
  };

  return (
    <View style={[styles.container, containerStyle]}>
      <TouchableOpacity style={styles.countryPicker} onPress={openModal}>
        <View style={[styles.flagContainer, flagContainerStyle]}>
          <Text style={styles.flag}>{selectedCountry.flag}</Text>
          <Icon
            name="chevron-down"
            size={chevronSize || 18}
            color={chevronColor || "#555"}
            style={styles.icon}
          />
        </View>
        <Text style={[styles.countryCode, countryCodeStyle]}>
          {selectedCountry.code}
        </Text>
      </TouchableOpacity>

      <TextInput
        style={[styles.phoneInput, phoneInputStyle]}
        keyboardType="phone-pad"
        placeholder={placeholder || "Enter phone number"}
        placeholderTextColor={placeholderTextColor || "#aaa"}
        returnKeyType="done"
        value={phoneNumber}
        onChangeText={handlePhoneNumberChange}
      />

      <Modal visible={isModalVisible} transparent animationType="none">
        <SafeAreaView style={styles.modalBackdrop}>
          <Animated.View
            style={[
              styles.modalContainer,
              {
                transform: [
                  {
                    translateY: slideAnim.interpolate({
                      inputRange: [0, 1],
                      outputRange: [600, 0],
                    }),
                  },
                ],
              },
            ]}
          >
            <TouchableOpacity
              style={[styles.closeButton, closeButtonStyle]}
              onPress={closeModal}
            >
              <Icon
                name="close"
                size={closeIconSize || 24}
                color={closeIconColor || "#FFF"}
              />
            </TouchableOpacity>

            <View style={[styles.searchContainer, searchContainerStyle]}>
              <Icon
                name="search"
                size={searchIconSize || 20}
                color={searchIconColor || "#555"}
                style={[styles.searchIcon, searchIconStyle]}
              />
              <TextInput
                style={[styles.searchInput, searchInputStyle]}
                placeholder="Search country"
                value={searchText}
                placeholderTextColor={placeholderTextColor || "#aaa"}
                onChangeText={setSearchText}
              />
            </View>

            <FlatList
              data={filteredCountries}
              keyExtractor={(item) => item.iso}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[styles.countryItem, countryItemStyle]}
                  onPress={() => selectCountry(item)}
                >
                  <Text style={[styles.flag, countryItemFlagStyle]}>
                    {item.flag}
                  </Text>
                  <Text style={[styles.countryName, countryItemNameStyle]}>
                    {item.name}
                  </Text>
                  <Text style={[styles.countryCode, countryItemCodeStyle]}>
                    {item.code}
                  </Text>
                </TouchableOpacity>
              )}
            />
          </Animated.View>
        </SafeAreaView>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    alignItems: "center",
    padding: 4,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: "#aaa",
  },
  countryPicker: {
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 5,
    paddingVertical: 5,
  },
  flagContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#f0f0f0",
    padding: 5,
    borderRadius: 5,
  },
  flag: {
    fontSize: 18,
    marginRight: 5,
  },
  countryCode: {
    fontSize: 16,
    fontWeight: "500",
    marginLeft: 10,
  },
  icon: {
    marginLeft: 0,
  },
  phoneInput: {
    flex: 1,
    fontSize: 16,
    paddingHorizontal: 10,
  },
  modalBackdrop: {
    flex: 1,
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    justifyContent: "flex-end",
  },
  modalContainer: {
    backgroundColor: "#fff",
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
    paddingTop: Platform.OS == "ios" ? StatusBar.currentHeight || 20 : 20,
    paddingBottom: 10,
    flex: 1,
  },
  closeButton: {
    alignSelf: "flex-end",
    padding: 5,
    marginRight: 10,
    backgroundColor: "red",
    borderRadius: 6,
  },
  searchContainer: {
    flexDirection: "row",
    alignItems: "center",
    borderWidth: 1,
    borderRadius: 5,
    borderColor: "#ccc",
    paddingHorizontal: 10,
    marginHorizontal: 20,
    marginVertical: 10,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    paddingVertical: 8,
  },
  countryItem: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 10,
    paddingHorizontal: 2,
    borderBottomWidth: 1,
    borderBottomColor: "#ccc",
    marginHorizontal: 22,
  },
  countryName: {
    fontSize: 16,
    flex: 1,
    marginLeft: 10,
  },
});

export default CountryPickerPhoneInput;
