import { Pressable, Text, TextInput, View } from "react-native";
import type { PhoneInputProps } from "../../types";
import { usePhoneCountryInput } from "../../hooks/usePhoneCountryInput";
import CountryPickerBottomSheet from "../country-picker/CountryPickerBottomSheet";
import { styles } from "./PhoneInput.styles";

const PhoneInput = ({
	value,
	onChangePhone,
	label = "Phone",
	placeholder = "Enter phone number",
	errorText,
	disabled = false,
	wrapperStyle,
	labelStyle,
	inputContainerStyle,
	inputStyle,
	errorTextStyle,
}: PhoneInputProps) => {

	const {
		selectedCountry,
		inputDigits,
		isCountryModalVisible,
		setIsCountryModalVisible,
		handlePhoneChange,
		handleSelectCountry,
	} = usePhoneCountryInput({
		value,
		onChangePhone,
	});

	return (
		<View style={wrapperStyle}>
			{label ? <Text style={[styles.label, labelStyle]}>{label}</Text> : null}

			<View style={[styles.inputWrap, inputContainerStyle]}>
				<Pressable
					accessibilityRole="button"
					accessibilityLabel="Select country"
					style={styles.flagButton}
					disabled={disabled}
					onPress={() => setIsCountryModalVisible(true)}
				>
					<Text style={styles.flagText}>{selectedCountry.flag}</Text>
				</Pressable>

				<Text style={[styles.dialCodeText, inputStyle]}>
					{selectedCountry?.dialCode}
				</Text>

				<TextInput
					value={inputDigits}
					onChangeText={handlePhoneChange}
					placeholder={placeholder}
					placeholderTextColor="#98A2B3"
					keyboardType="phone-pad"
					editable={!disabled}
					style={[styles.input, inputStyle]}
					maxLength={15}
				/>
			</View>

			{errorText ? (
				<Text style={[styles.errorText, errorTextStyle]}>{errorText}</Text>
			) : null}

			<CountryPickerBottomSheet
				visible={isCountryModalVisible}
				selectedCountryCode={selectedCountry.code}
				onClose={() => setIsCountryModalVisible(false)}
				onSelectCountry={handleSelectCountry}
			/>
		</View>
	);
};

export default PhoneInput;
