import { __ } from '@wordpress/i18n';
import React, { useState, useRef, useEffect } from 'react';
import { FilterPropertyValues } from '../FiltersControl';
import { closeSmall } from '@wordpress/icons';
import { Button, TextControl } from '@wordpress/components';

export interface FilterValueControlProps {
	value: string;
	propertyValues: FilterPropertyValues;
	onChange: ( value: string ) => void;
}

export const FilterValueControl = ( {
	value,
	propertyValues,
	onChange,
}: FilterValueControlProps ) => {
	const [ focusCustom, setFocusCustom ] = useState( false );
	const customInputRef = useRef< HTMLInputElement >();

	useEffect( () => {
		if ( focusCustom ) {
			customInputRef?.current?.focus();
			setFocusCustom( false );
		}
	}, [ focusCustom, customInputRef ] );

	return (
		<>
			{ value?.indexOf( 'gf_custom' ) !== 0 ? (
				// eslint-disable-next-line jsx-a11y/no-onchange
				<select
					className="gpeb-filter-value"
					onChange={ ( event ) => {
						onChange( event.target.value );

						/* Focus the custom input after selecting the custom option. */
						if ( event.target.value.indexOf( 'gf_custom' ) === 0 ) {
							setFocusCustom( true );
						}
					} }
					value={ value }
				>
					{ propertyValues ? (
						<>
							<option
								key={ 'enter_value' }
								value={ '' }
								disabled={ true }
								hidden={ true }
							>
								– { __( 'Value', 'gp-entry-blocks' ) } –
							</option>

							{ /* Special Values */ }
							<optgroup label={ __( 'Special Values', 'gp-entry-blocks' ) }>
								<option value="gf_custom">
									✎ { __( 'Custom Value', 'gp-entry-blocks' ) }
								</option>
								<option value="special_value:current_user:ID">
									{ __( 'Current User ID', 'gp-entry-blocks' ) }
								</option>
								<option value="special_value:current_post:ID">
									{ __( 'Current Post ID', 'gp-entry-blocks' ) }
								</option>
							</optgroup>

							{ propertyValues.map( ( propertyValue ) => (
								<option
									key={ propertyValue }
									value={ propertyValue }
								>
									{ propertyValue }
								</option>
							) ) }
						</>
					) : (
						<option value="">{ __( 'Loading…', 'gp-entry-blocks' ) }</option>
					) }
				</select>
			) : (
				<div className="gpeb-filter-value-custom">
					<TextControl
						value={ value.toString().replace( /^gf_custom:?/, '' ) }
						onChange={ ( newValue ) =>
							onChange( `gf_custom:${ newValue }` )
						}
						hideLabelFromVision={ true }
						label={ __( 'Custom Value', 'gp-entry-blocks' ) }
						ref={ customInputRef }
					/>

					<Button
						icon={ closeSmall }
						label={ __( 'Remove Custom Value', 'gp-entry-blocks' ) }
						onClick={ () => onChange( '' ) }
					/>
				</div>
			) }
		</>
	);
};
