import React from 'react';

import { ControlProps, PropEnum } from '../../../@types/settings.js';

import './CtrlEnum.scss';

interface CtrlEnumProps extends ControlProps {
	prop: PropEnum;
}

export default function CtrlEnum({
	currMod,
	updatePath,
	prop,
	value,
	inheritVal,
	deleteProp,
	updateProps,
}: CtrlEnumProps) {
	if (!prop.options) {
		return <div>Missing options for enum</div>;
	}

	const indexOfValue =
		prop.options.length && typeof prop.options[0] === 'object'
			? prop.options.findIndex((option: any) => option.value === value)
			: prop.options.indexOf(value);

	return (
		<React.Fragment>
			{prop.clearable !== false && value && !inheritVal && (
				<div
					className='ctrl-enum__clear-btn'
					onClick={() => deleteProp(updatePath)}
				>
					Clear
				</div>
			)}
			<select
				className={`ctrl-enum__select-dropdown ${
					inheritVal ? 'ctrl-enum__select-dropdown--inherit-val' : ''
				}`}
				value={!prop.allowOther || indexOfValue > -1 ? value : 'other'}
				onChange={(e) => updateProps(currMod.id, updatePath, e.target.value)}
			>
				{prop.options.map((option: any) =>
					typeof option === 'object' ? (
						<option
							key={option.value}
							value={option.value}
						>
							{option.label}
						</option>
					) : (
						<option
							key={option}
							value={option}
						>
							{option}
						</option>
					)
				)}
				{prop.allowOther && <option value='other'>Other</option>}
			</select>
			{prop.allowOther && indexOfValue === -1 && (
				<input
					key={currMod.id + updatePath}
					className='ctrl-enum__input'
					type='text'
					value={value}
					onChange={(e) => updateProps(currMod.id, updatePath, e.target.value)}
				/>
			)}
		</React.Fragment>
	);
}
