import React, { useCallback, useEffect } from 'react'
import { __, _x } from '@wordpress/i18n'
import domReady from '@wordpress/dom-ready'
import { useSnippetForm } from '../../../hooks/useSnippetForm'
import { ExplainSnippetButton } from './ExplainSnippetButton'

export const EDITOR_ID = 'snippet_description'

const TOOLBAR_BUTTONS = [
	[
		'bold',
		'italic',
		'underline',
		'strikethrough',
		'blockquote',
		'bullist',
		'numlist',
		'alignleft',
		'aligncenter',
		'alignright',
		'link',
		'wp_adv',
		'code_snippets'
	],
	[
		'formatselect',
		'forecolor',
		'pastetext',
		'removeformat',
		'charmap',
		'outdent',
		'indent',
		'undo',
		'redo',
		'spellchecker'
	]
]

const initializeEditor = (onChange: (content: string) => void) => {
	window.wp.editor?.initialize(EDITOR_ID, {
		mediaButtons: window.CODE_SNIPPETS_EDIT?.descEditorOptions.mediaButtons,
		quicktags: true,
		tinymce: {
			toolbar: TOOLBAR_BUTTONS.map(line => line.join(' ')),
			setup: editor => {
				editor.on('change', () => onChange(editor.getContent()))
			}
		}
	})
}

const GenerateDescriptionButton = () => {
	const { updateSnippet } = useSnippetForm()

	return (
		<ExplainSnippetButton
			field="desc"
			onResponse={generated => {
				updateSnippet(previous => ({
					...previous,
					name: generated.name && '' === previous.name.trim() ? generated.name : previous.name,
					desc: `${previous.desc}${generated.desc ? `\n<p>${generated.desc}</p>` : ''}`
				}))
			}}
		>
			{_x('Generate', 'generate snippet content', 'code-snippets')}
		</ExplainSnippetButton>
	)
}

const DescriptionEditorTextarea: React.FC = () => {
	const { snippet, setSnippet, isReadOnly } = useSnippetForm()

	const handleChange = useCallback(
		(desc: string) => setSnippet(previous => ({ ...previous, desc })),
		[setSnippet]
	)

	useEffect(() => {
		domReady(() => initializeEditor(handleChange))
	}, [handleChange])

	return (
		<textarea
			id={EDITOR_ID}
			className="wp-editor-area"
			onChange={event => handleChange(event.target.value)}
			autoComplete="off"
			disabled={isReadOnly}
			rows={window.CODE_SNIPPETS_EDIT?.descEditorOptions.rows}
			cols={40}
			value={snippet.desc}
		/>
	)
}

export const DescriptionEditor: React.FC = () =>
	window.CODE_SNIPPETS_EDIT?.enableDescription
		? <div className="snippet-description-container">
			<GenerateDescriptionButton />

			<h2>
				<label htmlFor={EDITOR_ID}>
					{__('Description', 'code-snippets')}
				</label>
			</h2>

			<DescriptionEditorTextarea />
		</div>
		: null
