import type { ActivityField } from '@/admin/api/activities';
import { Placeholder } from '@tiptap/extension-placeholder';
import { Underline } from '@tiptap/extension-underline';
import { EditorContent, useEditor } from '@tiptap/react';
import { BubbleMenu } from '@tiptap/react/menus';
import { StarterKit } from '@tiptap/starter-kit';
import { __ } from '@wordpress/i18n';

const BulletListIcon = () => (
	<svg
		width="13"
		height="13"
		fill="none"
		stroke="currentColor"
		strokeWidth="2"
		viewBox="0 0 24 24"
	>
		<line x1="9" y1="6" x2="20" y2="6" />
		<line x1="9" y1="12" x2="20" y2="12" />
		<line x1="9" y1="18" x2="20" y2="18" />
		<circle cx="4" cy="6" r="1.5" fill="currentColor" stroke="none" />
		<circle cx="4" cy="12" r="1.5" fill="currentColor" stroke="none" />
		<circle cx="4" cy="18" r="1.5" fill="currentColor" stroke="none" />
	</svg>
);

type Props = {
	field: Extract<ActivityField, { type: 'content' }>;
	onChange: (f: ActivityField) => void;
	onSlashTrigger: () => void;
};

type ToolbarButton = {
	label: React.ReactNode;
	title: string;
	action: () => void;
	active: boolean;
	cls?: string;
};

const Divider = () => (
	<div className="mx-[3px] h-4 w-px shrink-0 bg-white/15" />
);

const ContentBlock = ({ field, onChange, onSlashTrigger }: Props) => {
	const editor = useEditor({
		extensions: [
			StarterKit,
			Underline,
			// Paragraph.extend({
			// 	renderHTML({ node, HTMLAttributes }) {
			// 		// Ensure it renders 'p' instead of 'div'
			// 		return ['div', HTMLAttributes, 0];
			// 	},
			// }),
			Placeholder.configure({
				placeholder: __("Write something or type '/' for blocks…", 'allcoach'),
			}),
		],
		content: field.content,
		onUpdate: ({ editor }) => {
			const text = editor.getText();
			if (text.trim() === '/') {
				editor.commands.setContent('');
				onChange({ ...field, content: '' });
				onSlashTrigger();
				return;
			}
			onChange({ ...field, content: editor.getHTML() });
		},
		editorProps: {
			attributes: {
				class:
					'prose prose-sm max-w-none focus:outline-none text-[14px] text-gray-800',
			},
		},
	});

	const groups: ToolbarButton[][] = editor
		? [
				[
					{
						label: <b>B</b>,
						title: 'Bold',
						action: () => editor.chain().focus().toggleBold().run(),
						active: editor.isActive('bold'),
					},
					{
						label: <i>I</i>,
						title: 'Italic',
						action: () => editor.chain().focus().toggleItalic().run(),
						active: editor.isActive('italic'),
					},
					{
						label: <span className="underline">U</span>,
						title: 'Underline',
						action: () => editor.chain().focus().toggleUnderline().run(),
						active: editor.isActive('underline'),
					},
				],
				[
					{
						label: 'H1',
						title: 'Heading 1',
						action: () =>
							editor.chain().focus().toggleHeading({ level: 1 }).run(),
						active: editor.isActive('heading', { level: 1 }),
						cls: 'text-[11px]',
					},
					{
						label: 'H2',
						title: 'Heading 2',
						action: () =>
							editor.chain().focus().toggleHeading({ level: 2 }).run(),
						active: editor.isActive('heading', { level: 2 }),
						cls: 'text-[11px]',
					},
					{
						label: 'H3',
						title: 'Heading 3',
						action: () =>
							editor.chain().focus().toggleHeading({ level: 3 }).run(),
						active: editor.isActive('heading', { level: 3 }),
						cls: 'text-[11px]',
					},
				],
				[
					{
						label: <BulletListIcon />,
						title: 'Bullet list',
						action: () => editor.chain().focus().toggleBulletList().run(),
						active: editor.isActive('bulletList'),
					},
					// {
					// 	label: <QuoteIcon />,
					// 	title: 'Quote',
					// 	action: () => editor.chain().focus().toggleBlockquote().run(),
					// 	active: editor.isActive('blockquote'),
					// },
				],
			]
		: [];

	return (
		<div>
			{editor && (
				<BubbleMenu
					appendTo={document.body}
					editor={editor}
					options={{ placement: 'top-start', strategy: 'absolute' }}
					className="z-[99999]"
				>
					<div className="flex items-center gap-0.5 rounded-lg bg-[#1d2327] px-[7px] py-[5px] shadow-[0_4px_20px_rgba(0,0,0,0.25)]">
						{groups.flatMap((group, gi) => [
							...(gi > 0 ? [<Divider key={`div-${gi}`} />] : []),
							...group.map(({ label, title, action, active, cls }) => (
								<button
									key={title}
									type="button"
									title={title}
									onMouseDown={(e) => {
										e.preventDefault();
										action();
									}}
									className={`flex h-[26px] w-7 shrink-0 cursor-pointer items-center justify-center rounded-[5px] border-0 bg-transparent text-[13px] font-bold text-gray-200 transition-[background,color] duration-100 hover:bg-white/15 hover:text-white ${active ? 'bg-white/20 !text-teal-300' : ''} ${cls ?? ''}`}
								>
									{label}
								</button>
							)),
						])}
					</div>
				</BubbleMenu>
			)}
			<EditorContent editor={editor} />
		</div>
	);
};

export default ContentBlock;
