import countries from 'countries-phone-masks';
import {
  CountryCode,
  getCountries,
  getCountryCallingCode,
} from 'libphonenumber-js';
import { useRef, useState } from 'react';
import { useOnClickOutside } from 'usehooks-ts';
import { ChevronUpIcon } from './icons/ChevronUpIcon';
import { ChevronDownIcon } from './icons/ChevronDownIcon';

export function SelectPhoneCode({
  currentPhoneCodeAndCountry: [currentPhoneCode, currentCountry],
  onClick,
}: {
  currentPhoneCodeAndCountry: [string, CountryCode];
  onClick: ([phoneCode, country]: [string, CountryCode]) => void;
}) {
  const [open, setOpen] = useState(false);

  const ref = useRef<HTMLDivElement>(null);

  useOnClickOutside(ref, () => setOpen(false));

  return (
    <div
      ref={ref}
      className="relative flex flex-col sm:w-1/3 min-w-[max(10vw,20%)]"
    >
      <button
        className="flex gap-x-1 justify-between items-center relative"
        onClick={e => {
          e.preventDefault();
          setOpen(prev => !prev);
        }}
      >
        <img
          src={countries.find(c => c.iso === currentCountry)?.flag}
          className="sm:w-6 w-4"
          alt=""
        />
        <p className="h4">{currentPhoneCode}</p>
        {open ? <ChevronUpIcon /> : <ChevronDownIcon />}
      </button>
      {open && (
        <div className="space-y-1 absolute z-10 bg-[#14161F] top-[100%] -left-1 border border-t-0 rounded-b-lg border-[#3D425C] max-h-[300px] overflow-y-auto overflow-x-hidden">
          {getCountries()
            .map(country => [`+${getCountryCallingCode(country)}`, country])
            .filter(
              ([phonecode, country]) =>
                phonecode !== currentPhoneCode || country !== currentCountry,
            )
            .map(([phoneCode, country]) => (
              <div
                key={country}
                className="flex items-center gap-x-1 hover:bg-[#3D425C] px-1"
                onClick={() => {
                  onClick([phoneCode, country as CountryCode]);
                  setOpen(false);
                }}
              >
                <img
                  src={countries.find(c => c.iso === country)?.flag}
                  alt=""
                  className="sm:w-6 w-4"
                />
                <p className="flex-1 h4 cursor-pointer py-1">{phoneCode}</p>
              </div>
            ))}
        </div>
      )}
    </div>
  );
}
