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

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

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

import {
	Dropdown as SkaDropdown,
	Radio,
} from '../../../../tailwind/inspector-controls'

import {
	useSkaBlocks,
	type TailwindFeatureConfig,
} from '../../../../tailwind'

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

const noop = () => {}

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

const SPACING_SUPPORTS: TailwindFeatureConfig['supports'] = {
	important: false,
	signed: false,
	arbitrary: false,
	variable: false,
	bare: false,
}

const SpacingPicker: React.FC<SpacingPickerProps> = ({
	value,
	onChange,
	...textControlProps
}) => {

	const {compiler} = useSkaBlocks()

	const options = useMemo(() => {
		const spacingOptions = compiler.getThemeKey('--spacing')
		const spacingValues = compiler.getThemeKey('--spacing', false)
		return Array.from(spacingOptions.entries()).map(([k, v]) => {
			return {
				label: k,
				tooltip: v,
				value: spacingValues.has(k) ? spacingValues.get(k)! : v,
			}
		})
	}, [compiler])

	const currentOption = options.find(({value: optionValue}) => optionValue === value)
	const displayValue = value ? (currentOption ? `${currentOption.label} (${currentOption.tooltip})` : value) : ''

	return (
		<SkaDropdown
			renderContent={() => (
				<Radio
					label={__('Spacing', 'ska-blocks')}
					pills
					isSmall
					supports={SPACING_SUPPORTS}
					options={options}
					value={value}
					onChange={onChange}
				/>
			)}
			renderToggle={({onToggle}) => (
				<TextControl
					value={displayValue}
					onChange={noop}
					onFocus={onToggle}
					__nextHasNoMarginBottom
					__next40pxDefaultSize
					{...textControlProps}
				/>
			)}
		/>
	)
}

export default SpacingPicker
