import * as React from 'react'
import {__, _x} from '@wordpress/i18n'

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

import {
	Modal,
	__experimentalVStack as VStack,
} from '@wordpress/components'

import {
	ColorIndicatorButton,
	ColorIndicatorContext,
	ColorPickerContext,
	RecordEditor,
	RecordEditorRecordContext,
} from '@ska/components'

import {
	ARRAY_UNIQUE,
} from '@ska/utils'

import {
	ColorTextControl,
} from '../../../../components'

import type {
	TextControlProps,
} from '@wordpress/components/build-types/text-control/types'

import {
	themePaletteDefaultValue,
	type ThemePaletteValue,
} from '../../../../tailwind/colors'

import './style.scss'

export const ThemePaletteControlContext = createContext<{
	defaultValue: Record<string, Record<string, string>>,
}>({
	defaultValue: {},
})

export interface ThemePaletteControlProps extends Omit<TextControlProps, 'value' | 'onChange'> {
	value: ThemePaletteValue
	onChange: (nextValue: ThemePaletteValue) => void
}

const ThemePaletteControl: React.FC<ThemePaletteControlProps> = ({
	value: initialValue = {} as ThemePaletteValue,
	onChange,
}) => {

	const {
		key,
	} = useContext(RecordEditorRecordContext)

	const {
		defaultValue,
	} = useContext(ThemePaletteControlContext)

	const {
		transformColorValue,
	} = useContext(ColorIndicatorContext)

	const value = [...Object.keys(themePaletteDefaultValue), ...Object.keys(initialValue)].filter(ARRAY_UNIQUE).reduce((acc, cur) => {
		acc[cur] = initialValue[cur] || ''
		return acc
	}, {} as ThemePaletteValue)

	const [isOpen, setIsOpen] = useState(false)

	const currentDefaultValue = 'DEFAULT' in value ? value['DEFAULT'] : ''

	return <>
		<ColorIndicatorButton
			className='ska-blocks__theme-palette-control'
			variant='secondary'
			colorValue={value['DEFAULT'] || 'transparent'}
			onClick={() => setIsOpen(!isOpen)}
			children={__('Edit', 'ska-blocks')}
		/>
		{isOpen && (
			<Modal
				title={`${__('Edit theme palette', 'ska-blocks')}: "${key}"`}
				size='large'
				onRequestClose={() => setIsOpen(false)}
			>
				<VStack>
					{currentDefaultValue && <style>{`.ska-blocks--use-global-theme { --color-${key}: ${transformColorValue(currentDefaultValue)}; }`}</style>}
					<ColorPickerContext.Provider value={{oklch: true}}>
						<RecordEditor<ThemePaletteValue>
							value={value}
							onChange={onChange}
							lockedKeys={Object.keys(defaultValue[key] || {}).concat(Object.keys(themePaletteDefaultValue))}
							ValueControl={ColorTextControl}
						/>
					</ColorPickerContext.Provider>
				</VStack>
			</Modal>
		)}
	</>
}

export default ThemePaletteControl
