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

import {
	ToggleControl,
	TextControl,
	TextareaControl,
	Button,
	Modal,
	__experimentalVStack as VStack,
} from '@wordpress/components'

import {
	store as blockEditorStore,
	// @ts-expect-error
} from '@wordpress/block-editor'

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

import {
	useSelect,
	useDispatch,
} from '@wordpress/data'

import {
	store as noticesStore,
} from '@wordpress/notices'

import type {
	tBlock,
} from '@ska/shared'

import {
	createVariation,
	useVariationOptionsEdit,
	type VariationSlug,
} from '..'

export interface CreateVariationProps {
	clientId: string,
	onCreated: (slug: VariationSlug) => void
	onRequestClose: () => void
}

const CreateVariation: React.FC<CreateVariationProps> = ({
	clientId,
	onCreated,
	onRequestClose,
}) => {

	const [, dispatch] = useVariationOptionsEdit()
	const [name, setName] = useState('')
	const [description, setDescription] = useState('')
	const [includeContent, setIncludeContent] = useState(false)

	const block: tBlock = useSelect(select => select(blockEditorStore).getBlock(clientId), [clientId])

	const {
		createSuccessNotice,
		createErrorNotice,
	} = useDispatch(noticesStore)

	const onCreate = () => {

		if(!name) {
			createErrorNotice(__('Variation name is required', 'ska-blocks'), {type: 'snackbar'})
			return
		}

		const variationAttributes = createVariation(block, {
			includeContent,
		})

		const createdSlug = dispatch.addVariation({
			title: name,
			description,
			block: block.name,
			variation: JSON.stringify(variationAttributes),
		})

		createSuccessNotice(sprintf(__('Created variation "%s"', 'ska-blocks'), name), {type: 'snackbar'})
		onCreated(createdSlug)
		onRequestClose()
	}

	return (
		<Modal
			title={__('Create block variation', 'ska-blocks')}
			onRequestClose={onRequestClose}
			style={{maxWidth: 440}}
		>
			<VStack>
				<p>{__(`Add a new block that has current styles, presets, attributes and inner blocks applied by default.`, 'ska-blocks')}</p>
				<TextControl
					label={__('Variation name', 'ska-blocks')}
					value={name}
					onChange={setName}
					__nextHasNoMarginBottom
					__next40pxDefaultSize
				/>
				<TextareaControl
					label={__('Variation description', 'ska-blocks')}
					value={description}
					onChange={setDescription}
					__nextHasNoMarginBottom
				/>
				<ToggleControl
					label={__('Include content', 'ska-blocks')}
					checked={includeContent}
					onChange={() => setIncludeContent(!includeContent)}
					__nextHasNoMarginBottom
				/>
				<Button
					variant='primary'
					children={__('Create', 'ska-blocks')}
					disabled={!name}
					onClick={onCreate}
				/>
			</VStack>
		</Modal>
	)
}

export default CreateVariation
