'use client';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import clsx from 'clsx';
import { useLocale } from 'next-intl';
import { useState } from 'react';
import { getCountries } from 'react-phone-number-input/input';
import ar from 'react-phone-number-input/locale/ar';
import en from 'react-phone-number-input/locale/en';
import FallbackImage from './FallbackImage';



/**
* @author: Ahmed Badran
 * Created At: 27-10-2024
 * A country select component, which shows a flag of the selected country.
 *
 * @param {{ value: string, onChange: (country: string) => void, labels: Record<string, string>, placeholder: string, className: string }} props
 *
 * @returns {JSX.Element}
 */

export default function CountrySelect({ value, onChange, placeholder, className, ...rest }) {
   const [selectedCountry, setSelectedCountry] = useState(value);
   const locale = useLocale();
   const labels = locale === 'ar' ? ar : en;

   const handleChange = (value) => {
      const country = value
      setSelectedCountry(country);
      onChange(country);
   };

   return (
      <div className="relative">
         <Select
            {...rest}
            value={value}
            dir={locale === 'ar' ? 'rtl' : 'ltr'}
            onValueChange={handleChange}
         >
            <SelectTrigger className={clsx(className, {
               'first:indent-10': selectedCountry,
            })}>
               <SelectValue placeholder={placeholder} />
            </SelectTrigger>
            <SelectContent className="max-h-60">
               {getCountries().map((country) => (
                  <SelectItem key={country} value={country}>
                     {labels[country]}
                  </SelectItem>
               ))}
            </SelectContent>
         </Select>
         {selectedCountry && (
            <FallbackImage
               src={`https://purecatamphetamine.github.io/country-flag-icons/3x2/${selectedCountry}.svg`} // Assuming you have flag images stored in the `/flags` folder
               width={30}
               height={30}
               alt={selectedCountry}
               className='absolute top-1/2 start-3 -translate-y-1/2'
            />
         )}
      </div>
   );
}


