import React, { useCallback, useEffect, useMemo, useState } from "react";
import { FlatList, Text, TextInput } from "react-native";
import type { CountryItem, PhoneCountrySelectorSheetProps } from "../../types";
import { filterCountries } from "../../utils/phoneCountry";
import { CountryRow } from "./CountryRow";
import { styles } from "./CountryPickerBottomSheet.styles";
import AnimatedBottomSheet from "./AnimatedBottomSheet";

const CountryPickerBottomSheet = ({
	visible,
	selectedCountryCode,
	onClose,
	onSelectCountry,
}: PhoneCountrySelectorSheetProps) => {
	const [searchText, setSearchText] = useState("");

	useEffect(() => {
		if (!visible) {
			setSearchText("");
		}
	}, [visible]);

	const filteredCountries = useMemo(
		() => filterCountries(searchText),
		[searchText],
	);

	const handleSelect = useCallback(
		(country: CountryItem) => {
			onSelectCountry(country);
			setSearchText("");
		},
		[onSelectCountry],
	);

	const renderItem = useCallback(
		({ item }: { item: CountryItem }) => (
			<CountryRow
				item={item}
				isSelected={item.code === selectedCountryCode}
				onPress={handleSelect}
			/>
		),
		[handleSelect, selectedCountryCode],
	);

	return (
		<AnimatedBottomSheet
			visible={visible}
			onClose={onClose}
			heightRatio={0.75}
			backdropLabel="Close country selector"
		>
			<Text style={styles.sheetTitle}>Select Country</Text>
			<TextInput
				value={searchText}
				onChangeText={setSearchText}
				placeholder="Search country or code"
				placeholderTextColor="#98A2B3"
				style={styles.searchInput}
			/>
			<FlatList
				data={filteredCountries}
				keyExtractor={(item) => item.code}
				keyboardShouldPersistTaps="handled"
				initialNumToRender={20}
				style={styles.list}
				renderItem={renderItem}
			/>
		</AnimatedBottomSheet>
	);
};

export default CountryPickerBottomSheet;
