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

import {
	useRef,
} from '@wordpress/element'

import {
	BaseControl,
	TextControl,
	Dropdown,
} from '@wordpress/components'

import {
	Button,
	ColorIndicator,
	ColorPicker,
} from '@ska/components'

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

import './style.scss'

export interface ColorTextControlProps extends Omit<TextControlProps, 'value'> {
	value: string
	displayValue?: string
	disabled?: boolean
	colorDisabled?: boolean
	popoverProps?: Record<string, any>
	onFocus?: () => void
}

const ColorTextControl: React.FC<ColorTextControlProps> = ({
	value = '',
	displayValue,
	onChange,
	popoverProps = {},
	disabled = false,
	colorDisabled = false,
	...props
}) => {

	const inputRef = useRef<HTMLInputElement>(null)

	return (
		<BaseControl className='ska-blocks__color-text-control ska-blocks--use-code-inputs' __nextHasNoMarginBottom>
			<Dropdown
				className='ska-blocks__color-text-control__indicator'
				contentClassName='ska-blocks__color-text-control__picker'
				popoverProps={{
					placement: 'left',
					offset: 6,
					shift: true,
					...popoverProps,
				}}
				renderContent={() => (
					<ColorPicker
						color={value}
						onChange={onChange}
						enableAlpha
					/>
				)}
				renderToggle={({isOpen, onToggle}) => colorDisabled ? (
					<Button
						onClick={() => {
							if(inputRef.current) {
								inputRef.current?.focus()
							}
						}}
					>
						<ColorIndicator colorValue={value} />
					</Button>
				) : (
					<Button
						aria-expanded={isOpen}
						aria-haspopup='true'
						aria-label={__('Open colorpicker', 'ska-blocks')}
						disabled={disabled}
						onClick={onToggle}
					>
						<ColorIndicator colorValue={value} />
					</Button>
				)}
			/>
			<TextControl
				value={displayValue || value}
				onChange={onChange}
				disabled={disabled}
				ref={inputRef}
				__nextHasNoMarginBottom
				__next40pxDefaultSize
				{...props}
			/>
		</BaseControl>
	)
}

export default ColorTextControl
