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';
import { ClassNameWrapper } from '../hocs/ClassNameWrapper';

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 min-w-[75px]">
      <button
        className="relative flex items-center justify-between gap-x-1"
        onClick={e => {
          e.preventDefault();
          setOpen(prev => !prev);
        }}
      >
        <img
          src={countries.find(c => c.iso === currentCountry)?.flag}
          className="w-4 sm:w-6"
          alt={currentCountry}
        />
        <p className="h4">{currentPhoneCode}</p>
        <ClassNameWrapper
          className="flex-1 max-sm:w-4 sm:max-lg:w-5"
          element={open ? <ChevronUpIcon /> : <ChevronDownIcon />}
        />
      </button>
      {open && (
        <div className="space-y-1 absolute w-[120%] 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={country}
                  className="w-4 sm:w-6"
                />
                <p className="flex-1 py-1 cursor-pointer h4">{phoneCode}</p>
              </div>
            ))}
        </div>
      )}
    </div>
  );
}
