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

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

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

import {
	Attribute,
	VARIANT_DEFAULT_STATE,
} from '../../../tailwind/attributes'

import type {
	TailwindFeature,
	TailwindFeatureAttribute,
	SkaBlocksActionTypes,
} from '../../../types'

export interface EditVariantsProps {
	id: TailwindFeature['id']
	currentVariants?: TailwindFeatureAttribute[Attribute.VARIANTS]
	dispatch: SkaBlocksActionTypes
}

const EditVariants: React.FC<EditVariantsProps> = ({
	id,
	currentVariants = {},
	dispatch,
}) => {

	const variants = Object.keys(currentVariants).filter(v => v !== VARIANT_DEFAULT_STATE)

	return (
		<ArrayEditor
			id='ska-variants-editor'
			className='ska-blocks--use-code-inputs'
			value={variants}
			emptyPlaceholder={false}
			onChange={(nextVariants, index, action) => {
				switch(action) {
					case 'add-row':
						focusElement('#ska-add-variant')
					break
					case 'update-row':
						if(!variants.includes(nextVariants[index])) {
							dispatch.updateVariant({feature: id, variant: variants[index], nextVariant: nextVariants[index]})
						}
					break
					case 'remove-row':
						dispatch.removeVariant({feature: id, variant: variants[index]})
					break
					case 'move-up':
						dispatch.moveVariantUp({feature: id, variant: variants[index]})
					break
					case 'move-down':
						dispatch.moveVariantDown({feature: id, variant: variants[index]})
					break
				}
			}}
		/>
	)
}

export default EditVariants
