import {useEffect, useMemo, useRef, useState} from 'react';
import renderHtmlAttributes from "../../utils/renderHtmlAttributes";
import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess";
import uuid from "../../utils/uuid";

type FieldProps = {
	itemId: string
	height: number
	mode: 'visual-text' | 'visual' | 'text'
	activeMode: 'visual' | 'text'
	attrs: Record<string, string | string[]>
}

const wp = (window as any).wp;

const Field = (props: FieldProps) => {

	const inputRef = useRef<HTMLTextAreaElement>(null);
	const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]);
	const uniqueId = useRef(`${attrs.id}-${uuid()}`);

	const editorRef = useRef<any>(null);
	const [value, setValue] = useState(attrs.value?.trim() ?? '');

	// Reset after form submit
	useFormSubmitSuccess(inputRef, () => {
		const trimVal = attrs.value?.trim() ?? '';
		if (editorRef.current) {
			editorRef.current.setContent(trimVal);
		}
		setValue(trimVal);
	}, [attrs.value]);

	// Editor init
	useEffect(() => {
		const editorId = uniqueId.current;
		wp.editor?.remove(editorId);
		wp.editor.initialize(editorId, {
			...((props.mode === 'visual-text' || props.mode === 'visual') && {
				tinymce: {
					height: props.height,
					wpautop: true,
					statusbar: true,
					plugins: 'charmap,colorpicker,hr,lists,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpautoresize,wpeditimage,wpemoji,wpgallery,wplink,wpdialogs,wptextpattern,wpview',
					toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,spellchecker,fullscreen,wp_adv',
					toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help',
					menubar: false,
					tabfocus_elements: ':prev,:next',
					body_class: 'locale-en-us',
					teeny: false,
					indent: false,
					fix_list_elements: true,
					elementpath: true,
					setup(editor: any) {
						editorRef.current = editor;
						editor.on('change keyup NodeChange', () => setValue(editor.getContent()));
						editor.on('init', () => {
							if (props.mode !== 'visual-text') {
								return;
							}
							if (props.activeMode === 'visual') {
								(window as any).switchEditors.go(editorId, 'tmce');
							} else if (props.activeMode === 'text') {
								(window as any).switchEditors.go(editorId, 'html');
							}
						});
					}
				},
			}),
			...((props.mode === 'visual-text' || props.mode === 'text') && {
				quicktags: {
					buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,close'
				},
			}),
			mediaButtons: false,
			drag_drop_upload: false,
			_content_editor_dfw: false,
			teeny: false
		});

		return () => {
			wp.editor?.remove(editorId);
		}
	}, [attrs.id, props.activeMode, props.height, props.mode]);

	if (props.mode === 'text') {
		return <div className={'wp-core-ui wp-editor-wrap html-active'}>
			<div className="wp-editor-container">
				<textarea
					ref={inputRef}
					{...attrs}
					id={uniqueId.current}
					value={value}
					onChange={(event) => {
						setValue(event.target.value);
					}}
				></textarea>
			</div>
		</div>;
	}

	return (
		<>
			<input type="hidden" id={attrs.id} defaultValue={value}/>
			<textarea
				ref={inputRef}
				{...attrs}
				id={uniqueId.current}
				value={value}
				onChange={(event) => {
					setValue(event.target.value);
				}}
			></textarea>
		</>
	);
};

export default Field;
