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

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

import {
	TailwindFeatureContext,
	Radio,
} from '..'

import {
	parseVariantValue,
} from '../../classNames'

import type {
	ControlProps,
} from '.'

const Pills: React.FC<ControlProps> = ({
	label,
	controls,
	supports,
	variant,
	valueKey,
	value: inputValue,
	arbitraryValues = [],
	dispatch,
}) => {

	const {
		id,
		getOptions,
	} = useContext(TailwindFeatureContext)

	const options = getOptions(arbitraryValues) as Map<string, string>

	const {
		withPrefixSuffix,
		cleanValue: currentValue,
	} = parseVariantValue(inputValue)

	return (
		<Radio.Optimistic
			label={label}
			hideLabelFromVision={controls.length < 2}
			pills
			isSmall
			supports={supports}
			options={options}
			arbitraryValues={arbitraryValues}
			value={withPrefixSuffix(currentValue)}
			onChange={nextValue => {
				dispatch.setVariantValue({feature: id, variant, key: valueKey, value: nextValue})
			}}
			onAdd={valueToAdd => {
				dispatch.batch([
					...(!options.has(valueToAdd) ? [
						dispatch.actions.addArbitraryValue({feature: id, value: valueToAdd}),
					] : []),
					...(currentValue !== valueToAdd ? [
						dispatch.actions.setVariantValue({feature: id, variant, key: valueKey, value: valueToAdd}),
					] : []),
				])
			}}
			onUpdate={(nextValue, prevValue) => {
				dispatch.updateArbitraryValue({feature: id, nextValue, prevValue})
			}}
			onRemove={valueToRemove => {
				dispatch.removeArbitraryValue({feature: id, value: valueToRemove})
			}}
		/>
	)
}

export default Pills
