import {countries, TCountries} from "countries-list";
import {Fragment, useState} from "react";
import {Combobox, Transition} from "@headlessui/react";
import {BsChevronExpand} from "react-icons/bs";
import countryCodes from "country-codes-list";

interface Props {
	value?: string;
	onChange?: (value: string) => void;
	disabled?: boolean;
}

const mapCountries = (codes: string[]) => {
	return codes.map((code) => ({
		label: `${countryCodes.findOne("countryCode" as any, code).flag} ${countries[code as unknown as keyof TCountries].name} (+${
			countries[code as unknown as keyof TCountries].phone
		})`,
		code,
	}));
};

export default function CountrySelect({value, disabled = false, onChange}: Props) {
	const [query, setQuery] = useState("");

	const filteredCountries =
		query === ""
			? mapCountries(Object.keys(countries))
			: mapCountries(
					Object.keys(countries).filter((x) =>
						countries[x as unknown as keyof TCountries].name.toLowerCase().includes(query.toLowerCase()),
					),
			  );

	return (
		<>
			<Combobox value={value} onChange={onChange} disabled={disabled}>
				<div className="relative mt-1">
					<div className="relative w-full cursor-default overflow-hidden ">
						<Combobox.Input
							className="py-6 w-full px-8 text-sm font-normal placeholder:text-mti-gray-cool bg-white disabled:bg-mti-gray-platinum/40 rounded-full border border-mti-gray-platinum focus:outline-none"
							onChange={(e) => setQuery(e.target.value)}
							displayValue={(code: string) => {
								const country = countries[code as unknown as keyof TCountries];

								return `${countryCodes.findOne("countryCode" as any, code)?.flag || ""} ${country?.name || "N/A"} (+${
									country?.phone || "N/A"
								})`;
							}}
						/>
						<Combobox.Button className="absolute inset-y-0 right-0 flex items-center pr-8">
							<BsChevronExpand />
						</Combobox.Button>
					</div>
					<Transition
						as={Fragment}
						leave="transition ease-in duration-100"
						leaveFrom="opacity-100"
						leaveTo="opacity-0"
						afterLeave={() => setQuery("")}>
						<Combobox.Options className="absolute z-20 mt-1 max-h-60 w-full overflow-auto rounded-xl bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
							{filteredCountries.length === 0 && query !== "" ? (
								<div className="relative cursor-default select-none py-2 px-4 text-gray-700">Nothing found.</div>
							) : (
								filteredCountries.map((country) => (
									<Combobox.Option
										key={country.code}
										value={country.code}
										className={({active}) =>
											`relative cursor-default select-none py-2 pl-10 pr-4 ${
												active ? "bg-mti-purple-light text-white" : "text-gray-900"
											}`
										}>
										{country.label}
									</Combobox.Option>
								))
							)}
						</Combobox.Options>
					</Transition>
				</div>
			</Combobox>
		</>
	);
}
