import { BaseControl, ColorPicker, Dropdown } from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { __ } from '@wordpress/i18n';

/**
 * Compact color field: a small swatch + value that opens the full color
 * picker in a popover (so it no longer dominates the form).
 */
const ColorField = ( { field, value, onChange } ) => {
	const currentValue =
		typeof value === 'string' && value ? value : field.default ?? '';
	const instanceId = useInstanceId( ColorField, 'color-field' );
	const controlId = field?.id ?? field?.name ?? instanceId;

	const handleChange = ( nextColor ) => {
		if ( typeof nextColor === 'string' ) {
			onChange( nextColor );
			return;
		}

		if ( nextColor && typeof nextColor === 'object' ) {
			if ( typeof nextColor.hex === 'string' ) {
				onChange( nextColor.hex );
				return;
			}

			if ( typeof nextColor.color === 'string' ) {
				onChange( nextColor.color );
			}
		}
	};

	return (
		<BaseControl
			id={ controlId }
			label={ field.label }
			help={ field.help }
			required={ field.required }
		>
			<Dropdown
				className="cliqthemes-ui-color-field"
				contentClassName="cliqthemes-ui-color-field__popover"
				popoverProps={ { placement: 'bottom-start' } }
				renderToggle={ ( { isOpen, onToggle } ) => (
					<button
						type="button"
						className="cliqthemes-ui-color-swatch"
						aria-expanded={ isOpen }
						onClick={ onToggle }
					>
						<span
							className="cliqthemes-ui-color-swatch__chip"
							style={ { backgroundColor: currentValue || '#ffffff' } }
						/>
						<span className="cliqthemes-ui-color-swatch__value">
							{ currentValue ||
								__( 'Pick a color', 'cliq-store-locator' ) }
						</span>
					</button>
				) }
				renderContent={ () => (
					<div className="cliqthemes-ui-color-field__picker">
						<ColorPicker
							color={ currentValue || '#000000' }
							onChange={ handleChange }
							onChangeComplete={ handleChange }
							enableAlpha={ false }
						/>
					</div>
				) }
			/>
		</BaseControl>
	);
};

export default ColorField;
