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

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

import {
	ButtonGroup,
} from '@ska/components'

import {
	useSkaBlocksDispatch,
} from '../../../../tailwind/reducer'

import type {
	tBlockAttributes,
	tBlockEditProps,
} from '@ska/shared'

import {
	createOptions,
} from './util'

import {
	isOptionSelector,
} from '../..'

import './style.scss'

export interface SelectorOptionsProps {
	attributes: tBlockAttributes
	setAttributes: tBlockEditProps['setAttributes']
}

const SelectorOptions: React.FC<SelectorOptionsProps> = ({
	attributes,
	setAttributes,
}) => {

	const {
		skaBlocksSelectors = {},
		skaBlocksOptions = {},
	} = attributes

	const dispatch = useSkaBlocksDispatch(attributes, setAttributes)

	const selectors = Object.keys(skaBlocksSelectors)
	if(!selectors.length) {
		return null
	}

	const optionSelectors = selectors.filter(isOptionSelector)
	if(!optionSelectors.length) {
		return null
	}

	const options = createOptions(optionSelectors)

	return <>
		<BaseControl
			id='ska-blocks-selector-options'
			className='ska-blocks__selector-options'
			label={__('Options', 'ska-blocks')}
			__nextHasNoMarginBottom
		>
			<VStack
				alignment='start'
				spacing={4}
			>
				{options.map(({type, label, options = []}) => {
					switch(type) {
						case 'toggle':
							return (
								<ToggleControl
									key={label}
									label={label}
									checked={!!skaBlocksOptions[label]}
									onChange={() => dispatch.setSelectorOption({option: label, value: !skaBlocksOptions[label]})}
									__nextHasNoMarginBottom
								/>
							)
						case 'select':
							return (
								<ButtonGroup.Radio
									key={label}
									isSmall
									pills
									label={label}
									options={[{label: 'DEFAULT', value: 'DEFAULT'}].concat(options.filter(v => v !== 'DEFAULT').map(option => ({label: option, value: option})))}
									value={skaBlocksOptions[label] || 'DEFAULT'}
									onChange={(nextValue) => dispatch.setSelectorOption({option: label, value: nextValue ? nextValue : 'DEFAULT'})}
								/>
							)
						default:
							return null
					}
				})}
			</VStack>
		</BaseControl>
	</>
}

export default SelectorOptions
