import { useCallback, useEffect, useMemo, useState } from "react"; import type { CountryItem } from "../types"; import { getLocalDigits, resolveCountryFromPhone, sanitizeDigits } from "../utils/phoneCountry"; interface UsePhoneCountryInputParams { value: string; onChangePhone: (value: string) => void; } interface UsePhoneCountryInputResult { selectedCountry: CountryItem; inputDigits: string; isCountryModalVisible: boolean; setIsCountryModalVisible: (value: boolean) => void; handlePhoneChange: (input: string) => void; handleSelectCountry: (country: CountryItem) => void; } export const usePhoneCountryInput = ({ value, onChangePhone }: UsePhoneCountryInputParams): UsePhoneCountryInputResult => { const [isCountryModalVisible, setIsCountryModalVisible] = useState(false); const [userSelectedCountryCode, setUserSelectedCountryCode] = useState("US"); const selectedCountry = useMemo( () => resolveCountryFromPhone(value, userSelectedCountryCode), [userSelectedCountryCode, value] ); const [inputDigits, setInputDigits] = useState(() => getLocalDigits(value, selectedCountry.dialCode) ); const handlePhoneChange = useCallback( (input: string) => { const digits = sanitizeDigits(input); setInputDigits(digits); onChangePhone(`${selectedCountry.dialCode}${digits}`); }, [onChangePhone, selectedCountry.dialCode] ); useEffect(() => { const nextDigits = getLocalDigits(value, selectedCountry.dialCode); setInputDigits((current) => (current === nextDigits ? current : nextDigits)); }, [selectedCountry.dialCode, value]); const handleSelectCountry = useCallback( (country: CountryItem) => { const currentDigits = sanitizeDigits(inputDigits); setUserSelectedCountryCode(country.code); setInputDigits(currentDigits); onChangePhone(`${country.dialCode}${currentDigits}`); setIsCountryModalVisible(false); }, [inputDigits, onChangePhone] ); return { selectedCountry, inputDigits, isCountryModalVisible, setIsCountryModalVisible, handlePhoneChange, handleSelectCountry }; };