import { Switch } from '@/components/ui/switch';
import { mergeAttributes, Node } from '@tiptap/core';
import {
	NodeViewWrapper,
	ReactNodeViewRenderer,
	type ReactNodeViewProps,
} from '@tiptap/react';
import { __ } from '@wordpress/i18n';
import { Calendar } from 'lucide-react';
import { nanoid } from 'nanoid';
import { useEffect, useRef, useState } from 'react';

type Attrs = { label: string; required: boolean };

declare module '@tiptap/core' {
	interface Commands<ReturnType> {
		date: {
			insertDate: (attrs?: {
				label?: string;
				required?: boolean;
			}) => ReturnType;
		};
	}
}

export const DateField = Node.create({
	name: 'date',
	group: 'block',
	atom: true,
	selectable: true,
	draggable: true,

	addAttributes() {
		return {
			label: { default: '' },
			required: { default: false },
			id: { default: nanoid() },
			autoFocus: { default: false, renderHTML: () => ({}) },
		};
	},

	parseHTML() {
		return [{ tag: 'div[data-type="date"]' }];
	},

	renderHTML({ HTMLAttributes }) {
		return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'date' })];
	},

	addNodeView() {
		return ReactNodeViewRenderer(DateFieldComponent);
	},

	addCommands() {
		return {
			insertDate:
				(attrs = {}) =>
				// eslint-disable-next-line @typescript-eslint/no-explicit-any
				({ chain }: any) =>
					chain()
						.insertContent({
							type: 'date',
							attrs: {
								label: attrs.label ?? '',
								required: attrs.required ?? false,
								autoFocus: true,
							},
						})
						.run(),
		};
	},
});

function DateFieldComponent({ node, updateAttributes }: ReactNodeViewProps) {
	const { label, required, autoFocus } = node.attrs as Attrs & {
		autoFocus: boolean;
	};
	const [attrs, setAttrs] = useState<Attrs>({ label, required });
	const labelRef = useRef<HTMLInputElement>(null);

	useEffect(() => {
		if (autoFocus) {
			labelRef.current?.focus();
			updateAttributes({ autoFocus: false });
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<NodeViewWrapper className="rounded border bg-gray-50 p-3">
			<div className="rounded-[9px] border border-gray-200 bg-white px-4 py-3.5 transition-colors focus-within:border-teal-400">
				<div className="mb-2.5 flex items-center">
					<span className="text-[10px] font-bold tracking-widest text-teal-500 uppercase">
						{__('Date', 'allcoach')}
					</span>
					<div className="ml-auto flex items-center gap-1.5">
						<span className="text-[11px] text-gray-400">
							{__('Required?', 'allcoach')}
						</span>
						<Switch
							size="sm"
							checked={attrs.required}
							onCheckedChange={(v) => {
								setAttrs((prev) => ({ ...prev, required: v }));
								updateAttributes({ required: v });
							}}
						/>
					</div>
				</div>
				<input
					ref={labelRef}
					value={attrs.label}
					onChange={(e) =>
						setAttrs((prev) => ({ ...prev, label: e.target.value }))
					}
					onBlur={() => updateAttributes({ label: attrs.label })}
					className="w-full border-b border-dashed border-gray-200 bg-transparent pb-1 text-[14px] font-semibold text-gray-800 outline-none placeholder:font-normal placeholder:text-gray-400 focus:border-teal-400"
					placeholder={__('Question…', 'allcoach')}
				/>
				<div className="mt-3 flex w-fit items-center gap-2 rounded-md border border-gray-100 bg-gray-50 px-3 py-2 text-[13px] text-gray-400">
					<Calendar className="size-3.5" />
					{__('Date picker…', 'allcoach')}
				</div>
			</div>
		</NodeViewWrapper>
	);
}
