import { forwardRef, useEffect, useImperativeHandle, useRef, SelectHTMLAttributes } from 'react';

type OptionType = { value: string | number; label: string };

export default forwardRef(function SelectInput(
    { className = '', isFocused = false, includeEmptyOption = true, options = [], ...props }: SelectHTMLAttributes<HTMLSelectElement> & { isFocused?: boolean, options: Array<OptionType>, includeEmptyOption?: boolean },
    ref
) {
    const localRef = useRef<HTMLSelectElement>(null);

    useImperativeHandle(ref, () => ({
        focus: () => localRef.current?.focus(),
    }));

    useEffect(() => {
        if (isFocused) {
            localRef.current?.focus();
        }
    }, [isFocused]);

    return (
        <select
            {...props}
            className={
                'text-black border-pink-600 focus:border-purple-800 rounded-md shadow-sm ' +
                className
            }
            ref={localRef}
        >
            {includeEmptyOption && <option value={""}>Válasszon...</option>}
            {options.map((option) => (
                <option key={option.value} value={option.value}>
                    {option.label}
                </option>
            ))}
        </select>
    );
});
