import React, { useEffect, useRef } from "react";

type GenericSelectProps = {
	onChange?: (elem:HTMLSelectElement) => void;
	name: string;
	items: HTMLOptionElement[];
	value: number;
};

export const GenericSelect:React.FC<GenericSelectProps> = (props) => {
	const selectRef = useRef<HTMLSelectElement>(null);

	// Substitute all spaces and special characters for '_'
	const htmlIdName = props.name.toLowerCase().replace(/\s|\W/g, '_');

	useEffect(() => {
		const selectElem = selectRef.current;
		if (!selectElem) return;

		selectElem.disabled = true;
		selectElem.options.length = 0;
		for (const option of props.items) {
			if (option.value == props.value.toString()) {
				option.selected = true;
			}
			selectElem.appendChild(option);
		}
		selectElem.disabled = false;
	}, [props.items]);

	return (
		<div>
			<label className="fLabel" htmlFor={`${htmlIdName}_select`}>{props.name}</label>
			<div>
				<select 
				id={`${htmlIdName}_select`} 
				className="inputBoxWithIcon"
				ref={selectRef}
				onChange={e => props.onChange(e.target)}></select>
			</div>
		</div>
	);
};