import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { useWordpressCustomData } from "../../services/WordpressFetchData.js";
import { useUser } from "../../hooks/useUser.jsx";

export default function CountrySelect() {
	const availableCountries = useWordpressCustomData("/available-countries");
	const { country, changeCountry } = useUser();

	const [isSubmenuOpen, setIsSubmenuOpen] = useState(false);

	if (!availableCountries || !country) return <div className='country-select'>Loading...</div>;

	function handleChangeCountry(key, value) {
		changeCountry({ name: value, iso: key });
		handleShowHideSubmenu();
	}
	function handleShowHideSubmenu() {
		setIsSubmenuOpen(!isSubmenuOpen);
	}

	const countryOptions = Object.keys(availableCountries).map((key, value) => (
		<li
			key={uuidv4()}
			className='country-select__option'
			onClick={() => handleChangeCountry(key, availableCountries[key])}>
			<img className='flag' src={`https://flagsapi.com/${key}/flat/32.png`} alt='' />
			{availableCountries[key]}
		</li>
	));

	if (!countryOptions) return;

	return (
		<div className='country-select'>
			<button className='country-select__toggle' onClick={handleShowHideSubmenu}>
				<img className='flag' src={`https://flagsapi.com/${country.iso}/flat/32.png`} alt='' />
				{country.name}
			</button>
			<ul className='country-select__country-list' aria-hidden={!isSubmenuOpen}>
				{countryOptions}
			</ul>
		</div>
	);
}
