import { Box, InputAdornment, ListItem, ListItemIcon, ListItemText, Menu, MenuItem, TextField, Typography, } from '@mui/material'; import { useMemo, useRef, useState, type RefObject } from 'react'; import { ArrowDown2 } from 'iconsax-react'; import ReactCountryFlag from 'react-country-flag'; import { useTranslation } from 'react-i18next'; import { countries, type Country } from '../../../data/countries'; import type { CountryCode } from '@/types/commonTypes'; import { Icon } from '@rkheftan/harmony-ui'; import { LTRBox } from '@/components/common/LTRBox'; import { Virtuoso } from 'react-virtuoso'; interface CountryCodeSelectorProps { show: boolean; value: CountryCode; onChange: (newValue: CountryCode) => void; menuAnchor: HTMLElement | null; onCloseFocusRef: RefObject; } export function CountryCodeSelector({ show, value, onChange, menuAnchor, onCloseFocusRef, }: CountryCodeSelectorProps) { const [anchorEl, setAnchorEl] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const open = Boolean(anchorEl); const searchInputRef = useRef(null); const menuWidth = menuAnchor ? menuAnchor.clientWidth : 'auto'; const { t, i18n } = useTranslation(['country', 'common']); const selectedCountry = countries.find((c) => c.phone === value) || countries[0]; const handleClick = () => setAnchorEl(menuAnchor); const handleClose = () => { setTimeout(() => setAnchorEl(null), 0); setTimeout(() => { onCloseFocusRef.current?.focus(); }, 100); setSearchTerm(''); }; const handleSelect = (country: Country) => { onChange(country.phone); handleClose(); }; const handleMenuEntered = () => { searchInputRef.current?.focus(); }; const filteredCountries = useMemo( () => countries.filter( (country) => t(country.label, { ns: 'country' }) .toLowerCase() .includes(searchTerm.toLowerCase()) || country.label.toLowerCase().includes(searchTerm.toLowerCase()) || country.phone.includes(searchTerm), ), [searchTerm, t], ); const initialIndex = useMemo(() => { const index = filteredCountries.findIndex((c) => c.phone === value); return Math.max(0, index); }, [filteredCountries, value]); return ( theme.transitions.create(['width', 'opacity'], { duration: theme.transitions.duration.standard, }), overflow: 'hidden', whiteSpace: 'nowrap', height: '200%', display: 'flex', alignItems: 'center', gap: 0.25, pl: show ? 0.25 : 0, '&:hover': { cursor: 'pointer' }, }} > {value} setSearchTerm(e.target.value)} /> {filteredCountries.length === 0 ? ( {t('messages.noResualtFound', { ns: 'common' })} ) : ( ( handleSelect(country)} sx={{ minHeight: '48px', '&.Mui-selected': { backgroundColor: 'action.selected', }, }} > {country.phone} )} computeItemKey={(_, country) => country.code} /> )} ); }