import { useMemo, useState } from '@wordpress/element';
import {
	Button,
	ComboboxControl,
	Modal,
	SelectControl,
} from '@wordpress/components';
import { __, sprintf, _n } from '@wordpress/i18n';
import { getFieldComponent, isEmptyValue } from './fields';

const BulkEditModal = ( {
	actions = [],
	count = 0,
	isSaving = false,
	onApply,
	onCancel,
} ) => {
	const [ actionId, setActionId ] = useState( actions[ 0 ]?.id ?? '' );
	const [ customFieldName, setCustomFieldName ] = useState( '' );
	const [ value, setValue ] = useState( undefined );
	const [ error, setError ] = useState( '' );

	const action = useMemo(
		() => actions.find( ( item ) => item.id === actionId ) ?? null,
		[ actionId, actions ]
	);
	const customFields = action?.fields ?? [];
	const field =
		action?.kind === 'custom-field'
			? customFields.find( ( item ) => item.name === customFieldName )
			: action?.field;
	const FieldComponent = field ? getFieldComponent( field ) : null;
	const renderNestedField = ( nestedField, overrides = {} ) => {
		const NestedComponent = getFieldComponent( nestedField );
		const nestedValue = overrides.value;

		return (
			<div
				key={ overrides.key ?? nestedField.name }
				className="cliqthemes-ui-form-field"
			>
				<NestedComponent
					field={ nestedField }
					value={ nestedValue }
					onChange={ overrides.onChange }
					values={ overrides.values ?? {} }
					formValues={ overrides.formValues ?? {} }
					errors={ overrides.errors ?? {} }
					renderField={ renderNestedField }
				/>
			</div>
		);
	};

	const changeAction = ( nextAction ) => {
		setActionId( nextAction );
		setCustomFieldName( '' );
		setValue( undefined );
		setError( '' );
	};

	const submit = () => {
		if ( ! action || ! field ) {
			setError(
				__( 'Choose what you want to update.', 'cliq-store-locator' )
			);
			return;
		}

		if ( isEmptyValue( value ) && value !== false && value !== 0 ) {
			setError( __( 'Choose or enter a value.', 'cliq-store-locator' ) );
			return;
		}

		setError( '' );
		onApply( {
			action,
			field,
			value,
		} );
	};

	return (
		<Modal
			className="cliqthemes-ui-bulk-modal"
			title={ sprintf(
				/* translators: %d: Number of selected records. */
				_n(
					'Update %d selected item',
					'Update %d selected items',
					count,
					'cliq-store-locator'
				),
				count
			) }
			onRequestClose={ onCancel }
			shouldCloseOnClickOutside={ ! isSaving }
		>
			<div className="cliqthemes-ui-bulk-modal__body">
				<SelectControl
					__next40pxDefaultSize
					__nextHasNoMarginBottom
					label={ __( 'Bulk action', 'cliq-store-locator' ) }
					value={ actionId }
					options={ actions.map( ( item ) => ( {
						value: item.id,
						label: item.label,
					} ) ) }
					onChange={ changeAction }
					disabled={ isSaving }
				/>

				{ action?.kind === 'custom-field' && (
					<ComboboxControl
						__next40pxDefaultSize
						__nextHasNoMarginBottom
						label={ __( 'Custom field', 'cliq-store-locator' ) }
						value={ customFieldName }
						options={ customFields.map( ( item ) => ( {
							value: item.name,
							label: item.label ?? item.name,
						} ) ) }
						onChange={ ( next ) => {
							setCustomFieldName( next ?? '' );
							setValue( undefined );
							setError( '' );
						} }
						disabled={ isSaving }
					/>
				) }

				{ FieldComponent && (
					<div className="cliqthemes-ui-bulk-modal__value">
						<FieldComponent
							field={ {
								...field,
								label:
									action?.kind === 'custom-field'
										? field.label
										: action.valueLabel ?? field.label,
								required: true,
							} }
							value={ value }
							onChange={ ( next ) => {
								setValue( next );
								setError( '' );
							} }
							values={ { [ field.name ]: value } }
							formValues={ { [ field.name ]: value } }
							errors={ {} }
							renderField={ renderNestedField }
						/>
					</div>
				) }

				{ action?.description && (
					<p className="cliqthemes-ui-bulk-modal__help">
						{ action.description }
					</p>
				) }
				{ error && (
					<p className="cliqthemes-ui-field-error">{ error }</p>
				) }
			</div>

			<div className="cliqthemes-ui-bulk-modal__actions">
				<Button
					variant="tertiary"
					onClick={ onCancel }
					disabled={ isSaving }
				>
					{ __( 'Cancel', 'cliq-store-locator' ) }
				</Button>
				<Button
					variant="primary"
					onClick={ submit }
					isBusy={ isSaving }
					disabled={ isSaving || ! field }
				>
					{ __( 'Apply update', 'cliq-store-locator' ) }
				</Button>
			</div>
		</Modal>
	);
};

export default BulkEditModal;
