/**
 * WordPress dependencies
 */
import { Button, CheckboxControl } from '@safe-wordpress/components';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import clsx from 'clsx';
import { OptionLabel } from '@nelio/forms/components';
import type { KeyboardEventHandler } from 'react';

/**
 * Internal dependencies
 */
import type { OptionItem } from '../types';

type EditableOptionItemProps = {
	readonly option: OptionItem;
	readonly isLabelOnFocus: boolean;
	readonly isValueOnFocus: boolean;
	readonly isDisabled?: boolean;
	readonly isRemoveDisabled: boolean;
	readonly onFocusLabel: () => void;
	readonly onFocusValue: () => void;
	readonly onSelectedChange: ( selected: boolean ) => void;
	readonly onChange: ( o: OptionItem ) => void;
	readonly onRemove: () => void;
	readonly onKeyDown?: KeyboardEventHandler< HTMLInputElement >;
};
export const EditableOptionItem = (
	props: EditableOptionItemProps
): JSX.Element => {
	const {
		option,
		isLabelOnFocus,
		isValueOnFocus,
		isDisabled,
		isRemoveDisabled,
		onFocusLabel,
		onFocusValue,
		onSelectedChange,
		onChange,
		onRemove,
		onKeyDown,
	} = props;
	const { label, selected, disabled, value } = option;

	return (
		<div
			className={ clsx(
				'nelio-forms-field__select-option-item',
				'nelio-form-field__value--select-option-item'
			) }
		>
			<CheckboxControl
				className="nelio-forms-field__select-option-item-checker"
				checked={ selected }
				autoComplete="off"
				disabled={ disabled }
				onChange={ onSelectedChange }
			/>
			<OptionLabel
				className="nelio-forms-field__select-option-label"
				label={ label }
				isInFocus={ isLabelOnFocus }
				onFocus={ onFocusLabel }
				onChange={ ( newValue ) =>
					onChange( { ...option, label: newValue } )
				}
				onKeyDown={ onKeyDown }
			/>
			<OptionLabel
				className="nelio-forms-field__select-option-value"
				label={ value }
				placeholder={ _x( 'Type value here…', 'user', 'nelio-forms' ) }
				isInFocus={ isValueOnFocus }
				onFocus={ onFocusValue }
				onChange={ ( newValue ) =>
					onChange( { ...option, value: newValue } )
				}
				onKeyDown={ onKeyDown }
			/>
			<Button
				className="nelio-forms-field__select-option-action"
				icon={ isDisabled || disabled ? 'lock' : 'unlock' }
				label={
					isDisabled || disabled
						? _x( 'Enable option', 'command', 'nelio-forms' )
						: _x( 'Disable option', 'command', 'nelio-forms' )
				}
				showTooltip={ true }
				isPressed={ isDisabled || disabled }
				onClick={ () =>
					onChange( { ...option, disabled: ! disabled } )
				}
			/>
			<Button
				className="nelio-forms-field__select-option-action"
				icon="trash"
				label={ _x( 'Remove option', 'command', 'nelio-forms' ) }
				showTooltip={ true }
				disabled={ isRemoveDisabled }
				onClick={ onRemove }
			/>
		</div>
	);
};
