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

import {
	Card,
	CardHeader,
	CardBody,
	CardFooter,
	Button,
} from '@wordpress/components'

import {
	isManagedPreset,
	usePreset,
	PresetActions,
	type PresetSlug,
} from '..'

const RenderPreview: React.FC<{css: string, className: string}> = ({css, className}) => {
	return <>
		<style>{css.replaceAll('ska-preset-selector', `${className}:not(#_):not(#_):not(#_)`)}</style>
		<div className={cx('ska-preset-preview', 'ska-blocks--use-global-theme', className)}>
			<span className='ska-preset-preview__text'>
				{_x('…', 'Preset placeholder text', 'ska-blocks')}
			</span>
		</div>
	</>
}

export interface PresetPreviewProps {
	/** Preset slug. */
	slug: PresetSlug
	/** Current block has this preset. */
	isActive: boolean
	/** Add preset callback. */
	onAddPreset: () => void
	/** Remove preset callback. */
	onRemovePreset: () => void
}

const PresetPreview: React.FC<PresetPreviewProps> = ({
	slug,
	isActive,
	onAddPreset,
	onRemovePreset,
}) => {

	const {
		title,
		cx: classNames,
		css,
	} = usePreset(slug)

	const className = `ska-preset-preview--${slug}`

	return (
		<Card
			className={cx('ska-presets-preview__preset', {
				'ska-presets-preview__preset--managed': isManagedPreset(slug),
			})}
			data-slug={slug}
			size='small'
		>
			<CardHeader>
				<h3>{title}</h3>
				<code>{classNames || `-`}</code>
			</CardHeader>
			<CardBody>
				<RenderPreview css={css} className={className} />
			</CardBody>
			<CardFooter>
				{!isActive && (
					<Button
						variant='primary'
						children={__('Add to block', 'ska-blocks')}
						onClick={() => onAddPreset()}
					/>
				)}
				{isActive && (
					<Button
						variant='secondary'
						children={__('Remove from block', 'ska-blocks')}
						onClick={() => onRemovePreset()}
					/>
				)}
				<PresetActions slug={slug} />
			</CardFooter>
		</Card>
	)
}

export default PresetPreview
