/**
 * WordPress dependencies
 */
import {
	Dropdown,
	Button,
	ColorPicker as WpColorPicker,
} from '@safe-wordpress/components';
import { useState } from '@safe-wordpress/element';

// =====
// TYPES
// =====

export type ColorPickerProps = {
	readonly label: string;
	readonly color?: string;
	readonly defaultValue?: string;
	readonly enabledAlpha?: boolean;
	readonly onChange: ( color: string ) => void;
};

// ======
// EXPORT
// ======

export const ColorPicker = ( {
	label,
	color,
	defaultValue = '#000000',
	onChange,
}: ColorPickerProps ): JSX.Element => {
	const [ currentColor, setCurrentColor ] = useState( color || defaultValue );
	const onColorChange = ( newColor: string ) => {
		setCurrentColor( newColor );
		onChange( newColor );
	};

	return (
		<Dropdown
			renderToggle={ ( { isOpen, onToggle } ) => (
				<Button
					variant="link"
					onClick={ onToggle }
					aria-expanded={ isOpen }
				>
					{ label }
				</Button>
			) }
			renderContent={ () => (
				<WpColorPicker
					color={ currentColor }
					onChange={ onColorChange }
					enableAlpha={ true }
				/>
			) }
		/>
	);
};
