import { useState } from 'react';
import { useEditor, EditorContent, useEditorState } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import { Bold, Italic, Underline, Link2, List, ListOrdered } from 'lucide-react';

/**
 * The plugin's own WYSIWYG editor (TipTap), used for content interventions like
 * `improvecontentsingle` — deliberately NOT the WordPress block editor. Plain
 * HTML in, plain HTML out (GBP/WP-friendly). Read-only mode powers the Current
 * and Preview tabs.
 *
 * Content styling overrides wp-admin's aggressive element styles with `!` so the
 * body renders at a readable size (wp-admin forces `p { font-size: 13px }`).
 */
const PROSE =
	'[&_.ProseMirror]:outline-none ' +
	'[&_p]:text-base! [&_p]:leading-relaxed [&_p]:my-3! ' +
	'[&_h1]:text-3xl! [&_h1]:font-bold! [&_h1]:my-4! [&_h1]:leading-tight ' +
	'[&_h2]:text-2xl! [&_h2]:font-bold! [&_h2]:my-4! [&_h2]:leading-tight ' +
	'[&_h3]:text-xl! [&_h3]:font-semibold! [&_h3]:my-3! ' +
	'[&_ul]:list-disc [&_ul]:pl-6! [&_ul]:my-3! ' +
	'[&_ol]:list-decimal [&_ol]:pl-6! [&_ol]:my-3! ' +
	'[&_li]:my-1! [&_li]:text-base! ' +
	'[&_a]:text-magenta-600! [&_a]:underline ' +
	'[&_strong]:font-semibold! [&_em]:italic';

const EXTENSIONS = [StarterKit.configure({ link: { openOnClick: false } })];

const ToolbarButton = ({ active, onClick, label, children }) => (
	<button
		type="button"
		// Keep the editor selection while clicking the toolbar.
		onMouseDown={(e) => e.preventDefault()}
		onClick={onClick}
		aria-label={label}
		aria-pressed={active}
		className={`inline-flex items-center justify-center w-8 h-8 rounded-md transition-colors cursor-pointer ${
			active
				? 'bg-muted text-foreground'
				: 'text-muted-foreground hover:bg-muted/60'
		}`}
	>
		{children}
	</button>
);

/**
 * Editable rich-text editor with a toolbar.
 *
 * @param {{ value?: string, onChange?: (html:string)=>void }} props
 */
export const RichTextEditor = ({ value = '', onChange }) => {
	const [linkOpen, setLinkOpen] = useState(false);
	const [linkUrl, setLinkUrl] = useState('');

	const editor = useEditor({
		extensions: EXTENSIONS,
		content: value,
		editable: true,
		immediatelyRender: false,
		onUpdate: ({ editor: ed }) => onChange?.(ed.getHTML()),
	});

	const state = useEditorState({
		editor,
		selector: (ctx) => ({
			bold: ctx.editor?.isActive('bold') ?? false,
			italic: ctx.editor?.isActive('italic') ?? false,
			underline: ctx.editor?.isActive('underline') ?? false,
			link: ctx.editor?.isActive('link') ?? false,
			bullet: ctx.editor?.isActive('bulletList') ?? false,
			ordered: ctx.editor?.isActive('orderedList') ?? false,
			block: ctx.editor?.isActive('heading', { level: 2 })
				? 'h2'
				: ctx.editor?.isActive('heading', { level: 3 })
					? 'h3'
					: 'p',
		}),
	});

	if (!editor) return null;

	const applyBlock = (v) => {
		const chain = editor.chain().focus();
		if (v === 'p') chain.setParagraph().run();
		else chain.toggleHeading({ level: v === 'h2' ? 2 : 3 }).run();
	};

	const toggleLink = () => {
		if (state.link) {
			editor.chain().focus().unsetLink().run();
			return;
		}
		setLinkUrl('');
		setLinkOpen(true);
	};

	const applyLink = () => {
		const url = linkUrl.trim();
		if (url) {
			editor
				.chain()
				.focus()
				.extendMarkRange('link')
				.setLink({ href: url })
				.run();
		}
		setLinkOpen(false);
	};

	return (
		<div className="rounded-2xl border border-border overflow-hidden text-left">
			<div className="flex flex-wrap items-center gap-1 border-b border-border bg-muted/30 px-2 py-1.5">
				<select
					value={state.block}
					onChange={(e) => applyBlock(e.target.value)}
					className="h-8 rounded-md border border-border bg-background px-2 small-medium text-foreground mr-1"
					aria-label="Text style"
				>
					<option value="p">Body</option>
					<option value="h2">Heading</option>
					<option value="h3">Subheading</option>
				</select>
				<ToolbarButton
					active={state.bold}
					onClick={() => editor.chain().focus().toggleBold().run()}
					label="Bold"
				>
					<Bold className="w-4 h-4" />
				</ToolbarButton>
				<ToolbarButton
					active={state.italic}
					onClick={() => editor.chain().focus().toggleItalic().run()}
					label="Italic"
				>
					<Italic className="w-4 h-4" />
				</ToolbarButton>
				<ToolbarButton
					active={state.underline}
					onClick={() =>
						editor.chain().focus().toggleUnderline().run()
					}
					label="Underline"
				>
					<Underline className="w-4 h-4" />
				</ToolbarButton>
				<ToolbarButton
					active={state.link}
					onClick={toggleLink}
					label="Link"
				>
					<Link2 className="w-4 h-4" />
				</ToolbarButton>
				<span className="w-px h-5 bg-border mx-1" />
				<ToolbarButton
					active={state.bullet}
					onClick={() =>
						editor.chain().focus().toggleBulletList().run()
					}
					label="Bullet list"
				>
					<List className="w-4 h-4" />
				</ToolbarButton>
				<ToolbarButton
					active={state.ordered}
					onClick={() =>
						editor.chain().focus().toggleOrderedList().run()
					}
					label="Numbered list"
				>
					<ListOrdered className="w-4 h-4" />
				</ToolbarButton>
			</div>

			{linkOpen && (
				<div className="flex items-center gap-2 border-b border-border bg-background px-3 py-2">
					<input
						type="url"
						value={linkUrl}
						onChange={(e) => setLinkUrl(e.target.value)}
						onKeyDown={(e) => {
							if (e.key === 'Enter') {
								e.preventDefault();
								applyLink();
							}
						}}
						placeholder="https://example.com"
						className="flex-1 h-8 rounded-md border border-input px-2 small-regular"
					/>
					<button
						type="button"
						onClick={applyLink}
						className="h-8 px-3 rounded-md bg-foreground text-background! small-medium cursor-pointer"
					>
						Add link
					</button>
					<button
						type="button"
						onClick={() => setLinkOpen(false)}
						className="h-8 px-3 rounded-md border border-border small-medium text-muted-foreground cursor-pointer"
					>
						Cancel
					</button>
				</div>
			)}

			<div className={`px-4 py-3 min-h-[220px] ${PROSE}`}>
				<EditorContent editor={editor} />
			</div>
		</div>
	);
};

/**
 * Read-only renderer for the same content (Current and Preview tabs).
 *
 * @param {{ html?: string }} props
 */
export const RichTextView = ({ html = '' }) => {
	const editor = useEditor({
		extensions: EXTENSIONS,
		content: html,
		editable: false,
		immediatelyRender: false,
	});

	if (!editor) return null;

	return (
		<div
			className={`rounded-2xl border border-border px-6 py-4 text-left ${PROSE}`}
		>
			<EditorContent editor={editor} />
		</div>
	);
};
