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

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

import {
	__experimentalHStack as HStack,
	Button,
	Modal,
} from '@wordpress/components'

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

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

import {
	svgMinify,
} from './util'

import SVGStringRenderer from '../../blocks/image/SVGStringRenderer'

import {
	html_beautify,
	// @ts-expect-error
} from 'js-beautify'

const HTML_BEAUTIFY_SETTINGS = {
	'indent_size': '1',
	'indent_char': '\t',
	'max_preserve_newlines': '-1',
	'preserve_newlines': false,
	'end_with_newline': false,
}

import './style.scss'

export interface SVGEditModalProps {
	title?: string
	svg?: string
	sanitize?: boolean
	onChange: (nextSvg: string) => void
	onRequestClose: () => void
}

const SVGEditModal: React.FC<SVGEditModalProps> = ({
	title = __('Edit SVG', 'ska-blocks'),
	svg = '',
	sanitize = true,
	onChange,
	onRequestClose,
}) => {

	const sanitizedSvg = useMemo(() => sanitize ? sanitizeSVG(svg) : svg, [svg, sanitize])

	return (
		<Modal
			title={title}
			size='fill'
			onRequestClose={onRequestClose}
			className='ska-svg-edit-modal'
		>
			<HStack justify='end'>
				<Button
					size='small'
					children={__('Minify', 'ska-blocks')}
					onClick={() => onChange(svgMinify(svg))}
				/>
				<Button
					size='small'
					children={__('Beautify', 'ska-blocks')}
					onClick={() => onChange(html_beautify(svg, HTML_BEAUTIFY_SETTINGS))}
				/>
			</HStack>
			<div className='ska-svg-edit-modal__content'>
				<CodeEditor
					placeholder='<svg...'
					value={svg}
					onChange={onChange}
				/>
				<div
					className='ska-svg-edit-modal__content__preview'
					aria-hidden
				>
					<SVGStringRenderer
						svg={sanitizedSvg}
					/>
				</div>
			</div>
		</Modal>
	)
}

export default SVGEditModal
