import {
	useState,
	useEffect
} from '@wordpress/element';

import {
	Popover,
	Button,
} from '@wordpress/components';

type Props = {
	units: { label: string, value: string }[],
	value: string,
	device: device,
	onChange: handleUnitChange
};

/**
 *	Unit select or text.
 */
export default function UnitField({
	units,
	value,
	device,
	onChange,
}:Props) {
	// console.log(units);

	const [isVisible, setIsVisible] = useState<boolean>(false);

	const toggleVisible = () => {
		setIsVisible((state) => !state);
	};

	const handleUnitButtonClick = (unitValue: string, device: device) => {

		if (value !== unitValue) {
			onChange(unitValue, device);
		}
		setIsVisible(false);
	}


	const currentUnit = units.find(unit => unit.value === value);

	return (
		<div className='apura-unit'>
			{units.length > 1 ? (
				<div className='apura-unit__wrap'>
					<button
						type='button'
						className='apura-unit__current'
						onClick={toggleVisible}
					>
						{currentUnit?.label || '-'}
					</button>
					{isVisible &&
						<Popover
							placement='bottom-end'
							onClose={() => setIsVisible(false)}
						>
							<div className='apura-unit__select'>
								{units.map((unit => (
									<div key={unit.value} className='apura-unit__select-item'>
										<button
											type='button'
											className={value === unit.value ? 'apura-unit__select-button current' : 'apura-unit__select-button'}
											onClick={() => handleUnitButtonClick(unit.value, device)}>
											{unit.label}
										</button>
									</div>
								)))}

							</div>
						</Popover>
					}
				</div>
			)
		:
			<span className='apura-unit__text'>{value || '-'}</span>
		}
		</div>
	);
}
