import * as React from 'react'

import {
	createContext,
	useContext,
} from '@wordpress/element'

import {
	ColorPicker as WPColorPicker,
} from '@wordpress/components'

import type {
	ColorPickerProps as WPColorPickerProps,
} from '@wordpress/components/build-types/color-picker/types'

import {
	colord,
} from 'colord'

import {
	rgbToOklch,
	oklchToRgb,
} from './util'

export const ColorPickerContext = createContext<{
	/** Convert return value to oklch. */
	oklch?: boolean,
}>({
	oklch: false,
})

export type ColorPickerProps = WPColorPickerProps

/**
 * WP color picker with oklch support.
 */
const ColorPicker: React.FC<ColorPickerProps> = props => {

	const {
		oklch = false,
	} = useContext(ColorPickerContext)

	const {
		color,
		onChange,
		...restProps
	} = props

	let colorValue = color
	if(oklch && color && color.indexOf('oklch(') === 0) {
		const rgb = oklchToRgb(color)
		if(rgb) {
			colorValue = colord(rgb).toHex()
		}
	}

	return (
		<WPColorPicker
			{...restProps}
			color={colorValue}
			onChange={value => {

				if(!onChange) {
					return
				}

				if(value && value[0] === '#' && oklch) {
					const color = colord(value)
					if(color.rgba) {
						onChange(rgbToOklch(color.rgba))
					}
				} else {
					onChange(value)
				}
			}}
		/>
	)
}

export default ColorPicker
