import * as React from 'react'

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

import {
	Button,
} from '@wordpress/components'

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

import {
	useCopyToClipboard,
} from '@wordpress/compose'

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

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

import './style.scss'

export interface PreProps {
	value: any
	/** Value is CSS, beautify. */
	css?: boolean
	style?: Record<string, string | number>
	/** Set to false to disable copy button. */
	copy?: boolean
}

const Pre: React.FC<PreProps> = ({
	value,
	css = false,
	copy = true,
	...props
}) => {

	const displayValue = useMemo(() => {

		if(css) {
			return css_beautify(value)
		}

		return JSON.stringify(value, null, '\t')
			.replaceAll('    ', '\t')
			.replaceAll(/\\n/g, '\n')
			.replaceAll('\\"', '"')
			.replaceAll('\\t', '\t')
			.replaceAll('\\r', '\n')
	}, [value, css])

	const {
		createSuccessNotice,
	} = useDispatch(noticesStore)

	const copyRef = useCopyToClipboard(
		() => displayValue,
		() => createSuccessNotice('Copied.', {type: 'snackbar'})
	)

	return (
		<div className='ska-components-pre'>
			<pre {...props}>{displayValue}</pre>
			{copy && (
				<Button
					className='ska-components-pre__copy-button'
					size='small'
					children='Copy'
					ref={copyRef}
				/>
			)}
		</div>
	)
}

export default Pre
