/**
 * External dependencies.
 */
import clsx from 'clsx';
import { QuestionMarkCircleIcon } from '@heroicons/react/20/solid';

const SelectInput = ({ id, label, description, helpText, value, options, setOption, className, order = '', loading = false, disabled = false, noDefaultOption = false, ...props }) => {

    const filteredOptions = options && Object.entries( options );

    const handleChange = e => {
        setOption( e.target.value, id );
    };

    return (
	<fieldset className={order}>
		<legend className='text-sm font-semibold leading-6 text-gray-900 flex items-center gap-2'>
			{label && label}
			{helpText && (
				<div className="relative group">
					<QuestionMarkCircleIcon className="h-4 w-4 text-gray-400 cursor-help" />
					<div className="absolute left-1/2 transform -translate-x-1/2 bottom-full mb-2 px-3 py-2 bg-gray-900 text-white text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none z-10 max-w-sm w-64 text-left">
						{helpText}
						<div className="absolute top-full left-1/2 transform -translate-x-1/2 border-4 border-transparent border-t-gray-900"></div>
					</div>
				</div>
			)}
		</legend>
		<p className='mt-1 text-sm leading-6 text-gray-600'>
			{description && description}
		</p>
			<select
				id={id}
				name={id}
				className={clsx(
					"block w-full rounded-md border-0 mt-4 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-gray-600  sm:text-sm sm:leading-6 max-w-none",
					className && className
				)}
				onChange={handleChange}
				value={value ?? ""}
				{...props}
				autoComplete='off'
				data-lpignore='true'
				data-form-type='other'
				disabled={disabled}
			>
			{!noDefaultOption ? (
				<option value=''>Select</option>
			) : (
				<option value=''></option>
			)}
				{loading ? (
					<option value="" disabled>Loading...</option>
				) : (
					filteredOptions &&
					filteredOptions.map(([key, value], index) => (
						<option
							key={key}
							value={key}
						>
							{value}
						</option>
					))
				)}
			</select>
		</fieldset>
	);
}

export default SelectInput;