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

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

import {
	Modal,
	SearchControl,
	__experimentalVStack as VStack,
} from '@wordpress/components'

import PresetPreview from './PresetPreview'

import {
	useFilteredPresets,
	usePresets,
	useResolvedBlockPresets,
	type PresetSlug,
} from '..'

import {
	InspectorControlsContext,
} from '../../../tailwind/inspector-controls'

export interface PresetsModalProps {
	onAddPreset: (slug: PresetSlug) => void
	onRemovePreset: (slug: PresetSlug) => void
	onRequestClose: () => void
}

const PresetsModal: React.FC<PresetsModalProps> = ({
	onAddPreset,
	onRemovePreset,
	onRequestClose,
}) => {

	const {
		attributes,
	} = useContext(InspectorControlsContext)

	const {
		skaBlocks = {},
	} = attributes

	const {
		p = [],
	} = skaBlocks

	const blockPresets = useResolvedBlockPresets(p)

	const {presets, info, filterTerm, setFilterTerm} = useFilteredPresets(usePresets())

	return (
		<Modal
			title={__('Presets', 'ska-blocks')}
			onRequestClose={onRequestClose}
			size='fill'
		>
			<VStack style={{paddingTop: 16}}>
				<SearchControl
					className='ska-blocks__presets-control__search'
					placeholder={__('Filter presets…', 'ska-blocks')}
					help={info}
					value={filterTerm}
					onChange={setFilterTerm}
					__nextHasNoMarginBottom
				/>
				<div className='ska-presets-preview'>
					{Object.keys(presets).map(slug => {

						const hasPreset = blockPresets.findIndex(({id: presetId}) => presetId === slug) !== -1

						return (
							<PresetPreview
								key={slug}
								slug={slug}
								isActive={hasPreset}
								onAddPreset={() => onAddPreset(slug)}
								onRemovePreset={() => onRemovePreset(slug)}
							/>
						)
					})}
				</div>
			</VStack>
		</Modal>
	)
}

export default PresetsModal
