// components/HotspotEditor.jsx
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { X, ChevronLeft, ChevronRight, Save, Trash2, Link2, CornerDownRight, Info, PlayCircle, ShoppingCart, MousePointerSquareDashed } from 'lucide-react';
import { fetchHotspots, saveHotspots, searchProducts } from '../api/pdfs';
import { getPDFJS } from '../utils/thumbnail';
import { useToast } from './Toast';

const ACTIONS = [
    ['link', 'Open a link', Link2],
    ['page', 'Go to a page', CornerDownRight],
    ['note', 'Show a note', Info],
    ['video', 'Play a video', PlayCircle],
    ['product', 'Add to cart', ShoppingCart],
];
const ACTION_ICON = Object.fromEntries(ACTIONS.map(([v, , Icon]) => [v, Icon]));

const newId = () => Math.random().toString(36).slice(2, 10);
const clamp = (v, min, max) => Math.min(max, Math.max(min, v));

const Field = ({ label, children, hint }) => (
    <label className="block">
        <span className="block text-xs font-medium text-slate-600 mb-1">{label}</span>
        {children}
        {hint && <span className="block mt-1 text-[11px] text-slate-400">{hint}</span>}
    </label>
);
const inputClass = 'block w-full px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-sm text-slate-900';

const ProductPicker = ({ value, onChange }) => {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState([]);
    useEffect(() => {
        const t = setTimeout(() => {
            searchProducts(query).then((res) => setResults(res.data.products)).catch(() => setResults([]));
        }, 250);
        return () => clearTimeout(t);
    }, [query]);
    return (
        <div className="space-y-2">
            <input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search products" className={inputClass} />
            <div className="max-h-48 overflow-y-auto rounded-lg border border-slate-200 divide-y divide-slate-100">
                {results.length === 0 && <p className="p-3 text-xs text-slate-500">No products found.</p>}
                {results.map((p) => (
                    <button
                        key={p.id}
                        type="button"
                        onClick={() => onChange(p.id)}
                        className={`flex w-full items-center gap-2 px-2.5 py-2 text-left text-sm ${value === p.id ? 'bg-indigo-50 text-indigo-800' : 'hover:bg-slate-50 text-slate-700'}`}
                    >
                        {p.image ? <img src={p.image} alt="" className="size-8 rounded object-cover" /> : <span className="size-8 rounded bg-slate-100" />}
                        <span className="min-w-0 flex-1 truncate">{p.name}</span>
                        <span className="text-xs text-slate-500">{p.price}</span>
                    </button>
                ))}
            </div>
        </div>
    );
};

/**
 * Full-screen editor: draw hotspots on a page, pick what they do, save.
 */
const HotspotEditor = ({ pdf, onClose, onSaved }) => {
    const { toast } = useToast();
    const [doc, setDoc] = useState(null);
    const [pageNum, setPageNum] = useState(1);
    const [hotspots, setHotspots] = useState(null);
    const [clicks, setClicks] = useState({});
    const [woo, setWoo] = useState(false);
    const [selected, setSelected] = useState(null);
    const [dirty, setDirty] = useState(false);
    const [saving, setSaving] = useState(false);
    const [size, setSize] = useState({ width: 0, height: 0 });
    const [draft, setDraft] = useState(null); // rectangle being drawn
    const canvasRef = useRef(null);
    const stageRef = useRef(null);
    const pageRef = useRef(null);
    const drag = useRef(null);

    // Load the PDF and saved hotspots
    useEffect(() => {
        let alive = true;
        (async () => {
            try {
                const pdfjs = await getPDFJS();
                const loaded = await pdfjs.getDocument(pdf.url).promise;
                if (alive) setDoc(loaded);
            } catch {
                toast('Could not open the PDF', { type: 'error' });
            }
        })();
        fetchHotspots(pdf.id)
            .then((res) => {
                if (!alive) return;
                setHotspots(res.data.hotspots);
                setClicks(res.data.clicks || {});
                setWoo(!!res.data.woocommerce);
            })
            .catch(() => alive && setHotspots([]));
        return () => { alive = false; };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pdf.id, pdf.url]);

    // Render the current page to fit the stage
    useEffect(() => {
        if (!doc || !stageRef.current) return undefined;
        let task = null;
        let cancelled = false;
        (async () => {
            const page = await doc.getPage(pageNum);
            if (cancelled) return;
            const stage = stageRef.current.getBoundingClientRect();
            const base = page.getViewport({ scale: 1 });
            const scale = Math.min((stage.width - 48) / base.width, (stage.height - 48) / base.height);
            const viewport = page.getViewport({ scale });
            const dpr = window.devicePixelRatio || 1;
            const canvas = canvasRef.current;
            canvas.width = Math.floor(viewport.width * dpr);
            canvas.height = Math.floor(viewport.height * dpr);
            canvas.style.width = `${viewport.width}px`;
            canvas.style.height = `${viewport.height}px`;
            setSize({ width: viewport.width, height: viewport.height });
            task = page.render({ canvasContext: canvas.getContext('2d'), viewport, transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined });
            await task.promise.catch(() => {});
        })();
        return () => {
            cancelled = true;
            task?.cancel();
        };
    }, [doc, pageNum]);

    const onPage = useMemo(() => (hotspots || []).filter((h) => h.page === pageNum), [hotspots, pageNum]);
    const current = (hotspots || []).find((h) => h.id === selected) || null;
    const pagesWith = useMemo(() => [...new Set((hotspots || []).map((h) => h.page))].sort((a, b) => a - b), [hotspots]);

    const update = useCallback((id, patch) => {
        setHotspots((list) => list.map((h) => (h.id === id ? { ...h, ...patch } : h)));
        setDirty(true);
    }, []);

    const remove = useCallback((id) => {
        setHotspots((list) => list.filter((h) => h.id !== id));
        setSelected(null);
        setDirty(true);
    }, []);

    // Pointer position as page fractions
    const point = (e) => {
        const r = pageRef.current.getBoundingClientRect();
        return { x: clamp((e.clientX - r.left) / r.width, 0, 1), y: clamp((e.clientY - r.top) / r.height, 0, 1) };
    };

    const onPointerDown = (e) => {
        if (e.button !== 0) return;
        const p = point(e);
        const handle = e.target.closest('[data-handle]');
        const box = e.target.closest('[data-hotspot]');
        if (handle && box) {
            const h = hotspots.find((x) => x.id === box.dataset.hotspot);
            drag.current = { mode: 'resize', id: h.id, start: p, orig: { ...h } };
        } else if (box) {
            const h = hotspots.find((x) => x.id === box.dataset.hotspot);
            setSelected(h.id);
            drag.current = { mode: 'move', id: h.id, start: p, orig: { ...h } };
        } else {
            setSelected(null);
            drag.current = { mode: 'draw', start: p };
            setDraft({ x: p.x, y: p.y, w: 0, h: 0 });
        }
        e.currentTarget.setPointerCapture(e.pointerId);
        e.preventDefault();
    };

    const onPointerMove = (e) => {
        const d = drag.current;
        if (!d) return;
        const p = point(e);
        if (d.mode === 'draw') {
            setDraft({ x: Math.min(d.start.x, p.x), y: Math.min(d.start.y, p.y), w: Math.abs(p.x - d.start.x), h: Math.abs(p.y - d.start.y) });
        } else if (d.mode === 'move') {
            const o = d.orig;
            update(d.id, { x: clamp(o.x + p.x - d.start.x, 0, 1 - o.w), y: clamp(o.y + p.y - d.start.y, 0, 1 - o.h) });
        } else if (d.mode === 'resize') {
            const o = d.orig;
            update(d.id, { w: clamp(o.w + p.x - d.start.x, 0.01, 1 - o.x), h: clamp(o.h + p.y - d.start.y, 0.01, 1 - o.y) });
        }
    };

    const onPointerUp = () => {
        const d = drag.current;
        drag.current = null;
        if (d?.mode === 'draw' && draft) {
            setDraft(null);
            if (draft.w < 0.015 || draft.h < 0.01) return; // a click, not a drag
            const h = { id: newId(), page: pageNum, ...draft, action: 'link', label: '', url: '', newTab: true };
            setHotspots((list) => [...list, h]);
            setSelected(h.id);
            setDirty(true);
        }
    };

    // Keyboard: Delete removes, arrows switch pages, Escape deselects/closes
    useEffect(() => {
        const onKey = (e) => {
            const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || '');
            if (typing) return;
            if ((e.key === 'Delete' || e.key === 'Backspace') && selected) {
                e.preventDefault();
                remove(selected);
            } else if (e.key === 'Escape') {
                e.stopPropagation(); // keep the PDF details panel open
                if (selected) setSelected(null);
                else onCloseRequest();
            } else if (e.key === 'ArrowRight' && doc) setPageNum((n) => Math.min(doc.numPages, n + 1));
            else if (e.key === 'ArrowLeft') setPageNum((n) => Math.max(1, n - 1));
        };
        window.addEventListener('keydown', onKey, true);
        return () => window.removeEventListener('keydown', onKey, true);
    });

    const onCloseRequest = () => {
        if (dirty && !window.confirm('Discard your unsaved hotspot changes?')) return;
        onClose();
    };

    const handleSave = async () => {
        setSaving(true);
        try {
            const res = await saveHotspots(pdf.id, hotspots);
            setHotspots(res.data.hotspots);
            setDirty(false);
            toast('Hotspots saved');
            onSaved?.(res.data.hotspots.length);
        } catch (err) {
            toast(err.message || 'Could not save hotspots', { type: 'error' });
        } finally {
            setSaving(false);
        }
    };

    const total = doc?.numPages || 0;

    return (
        <div className="pdfrack-hotspot-editor fixed inset-0 z-[100000] flex flex-col bg-slate-900/95" role="dialog" aria-label={`Hotspots for ${pdf.title || pdf.name}`}>
            <header className="flex shrink-0 items-center gap-4 border-b border-white/10 bg-slate-900 px-5 py-3 text-white" style={{ marginTop: 32 }}>
                <div className="min-w-0 flex-1">
                    <p className="text-[11px] font-semibold uppercase tracking-wider text-indigo-300">Hotspots</p>
                    <p className="truncate text-sm font-semibold">{pdf.title || pdf.name}</p>
                </div>
                <div className="flex items-center gap-1 rounded-lg bg-white/10 p-1">
                    <button type="button" onClick={() => setPageNum((n) => Math.max(1, n - 1))} disabled={pageNum <= 1} className="rounded-md p-1.5 hover:bg-white/10 disabled:opacity-40" aria-label="Previous page"><ChevronLeft className="size-4" /></button>
                    <span className="px-2 text-sm tabular-nums">Page <strong>{pageNum}</strong> / {total || '–'}</span>
                    <button type="button" onClick={() => setPageNum((n) => Math.min(total, n + 1))} disabled={!total || pageNum >= total} className="rounded-md p-1.5 hover:bg-white/10 disabled:opacity-40" aria-label="Next page"><ChevronRight className="size-4" /></button>
                </div>
                <button
                    type="button"
                    onClick={handleSave}
                    disabled={!dirty || saving}
                    className="inline-flex items-center gap-1.5 rounded-lg bg-indigo-500 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-400 disabled:opacity-50"
                >
                    <Save className="size-4" /> {saving ? 'Saving…' : dirty ? 'Save' : 'Saved'}
                </button>
                <button type="button" onClick={onCloseRequest} className="rounded-full p-2 text-slate-300 hover:bg-white/10 hover:text-white" aria-label="Close">
                    <X className="size-5" />
                </button>
            </header>

            <div className="flex min-h-0 flex-1">
                <div ref={stageRef} className="relative flex min-w-0 flex-1 items-center justify-center overflow-hidden">
                    {!doc && <span className="size-8 rounded-full border-2 border-white/20 border-t-white animate-spin" />}
                    <div
                        ref={pageRef}
                        className="relative bg-white shadow-2xl select-none"
                        style={{ width: size.width || undefined, height: size.height || undefined, cursor: 'crosshair', touchAction: 'none', display: doc ? 'block' : 'none' }}
                        onPointerDown={onPointerDown}
                        onPointerMove={onPointerMove}
                        onPointerUp={onPointerUp}
                    >
                        <canvas ref={canvasRef} className="block" />
                        {onPage.map((h) => {
                            const Icon = ACTION_ICON[h.action] || Link2;
                            const active = h.id === selected;
                            return (
                                <div
                                    key={h.id}
                                    data-hotspot={h.id}
                                    className={`absolute rounded-md border-2 ${active ? 'border-indigo-500 bg-indigo-500/20' : 'border-indigo-400/80 bg-indigo-400/15 hover:bg-indigo-400/25'}`}
                                    style={{ left: `${h.x * 100}%`, top: `${h.y * 100}%`, width: `${h.w * 100}%`, height: `${h.h * 100}%`, cursor: 'move' }}
                                >
                                    <span className="absolute -top-2.5 -left-2.5 flex size-5 items-center justify-center rounded-full bg-indigo-600 text-white shadow">
                                        <Icon className="size-3" />
                                    </span>
                                    {h.label && (
                                        <span className="pointer-events-none absolute left-1 top-1 max-w-[calc(100%-8px)] truncate rounded bg-indigo-600 px-1.5 py-px text-[10px] font-medium text-white">{h.label}</span>
                                    )}
                                    {active && (
                                        <span data-handle className="absolute -bottom-1.5 -right-1.5 size-3.5 rounded-sm border-2 border-white bg-indigo-600 shadow" style={{ cursor: 'nwse-resize' }} />
                                    )}
                                </div>
                            );
                        })}
                        {draft && (
                            <div className="pointer-events-none absolute rounded-md border-2 border-dashed border-indigo-500 bg-indigo-500/10"
                                style={{ left: `${draft.x * 100}%`, top: `${draft.y * 100}%`, width: `${draft.w * 100}%`, height: `${draft.h * 100}%` }} />
                        )}
                    </div>
                </div>

                <aside className="flex w-[320px] shrink-0 flex-col border-l border-slate-200 bg-white">
                    {current ? (
                        <div className="flex-1 overflow-y-auto p-5 space-y-4">
                            <div className="flex items-center justify-between">
                                <p className="text-sm font-semibold text-slate-900">Hotspot</p>
                                <button type="button" onClick={() => remove(current.id)} className="inline-flex items-center gap-1 text-xs font-semibold text-slate-500 hover:text-red-600">
                                    <Trash2 className="size-3.5" /> Delete
                                </button>
                            </div>
                            <div className="grid grid-cols-1 gap-1.5">
                                {ACTIONS.filter(([v]) => v !== 'product' || woo || current.action === 'product').map(([value, label, Icon]) => (
                                    <button
                                        key={value}
                                        type="button"
                                        onClick={() => update(current.id, { action: value })}
                                        className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-left text-sm ${current.action === value ? 'border-indigo-500 bg-indigo-50 text-indigo-900' : 'border-slate-200 text-slate-700 hover:bg-slate-50'}`}
                                    >
                                        <Icon className="size-4" /> {label}
                                    </button>
                                ))}
                            </div>
                            <Field label="Label" hint="Shown when the reader points at the hotspot.">
                                <input className={inputClass} value={current.label || ''} onChange={(e) => update(current.id, { label: e.target.value })} placeholder="e.g. Shop this look" />
                            </Field>
                            {current.action === 'link' && (
                                <>
                                    <Field label="Link">
                                        <input className={inputClass} type="url" value={current.url || ''} onChange={(e) => update(current.id, { url: e.target.value })} placeholder="https://" />
                                    </Field>
                                    <label className="flex items-center gap-2 text-sm text-slate-700">
                                        <input type="checkbox" checked={!!current.newTab} onChange={(e) => update(current.id, { newTab: e.target.checked })} className="size-4 appearance-auto accent-indigo-600" style={{ padding: 0 }} />
                                        Open in a new tab
                                    </label>
                                </>
                            )}
                            {current.action === 'page' && (
                                <Field label="Go to page">
                                    <input className={inputClass} type="number" min="1" max={total || undefined} value={current.target || 1} onChange={(e) => update(current.id, { target: clamp(Number(e.target.value) || 1, 1, total || 99999) })} />
                                </Field>
                            )}
                            {current.action === 'note' && (
                                <Field label="Note">
                                    <textarea className={inputClass} rows={5} value={current.text || ''} onChange={(e) => update(current.id, { text: e.target.value })} />
                                </Field>
                            )}
                            {current.action === 'video' && (
                                <Field label="Video" hint="A YouTube or Vimeo link, or a video file (MP4) address.">
                                    <input className={inputClass} type="url" value={current.url || ''} onChange={(e) => update(current.id, { url: e.target.value })} placeholder="https://www.youtube.com/watch?v=…" />
                                </Field>
                            )}
                            {current.action === 'product' && (
                                woo
                                    ? <Field label="Product"><ProductPicker value={current.productId} onChange={(productId) => update(current.id, { productId })} /></Field>
                                    : <p className="rounded-lg bg-amber-50 p-3 text-xs text-amber-800">WooCommerce is not active, so this hotspot is hidden from readers.</p>
                            )}
                            <p className="text-xs text-slate-400">
                                {clicks[current.id] ? `${clicks[current.id]} click${clicks[current.id] === 1 ? '' : 's'} so far` : 'No clicks yet'}
                            </p>
                        </div>
                    ) : (
                        <div className="flex-1 overflow-y-auto p-5">
                            <div className="rounded-xl bg-indigo-50 p-4 text-sm text-indigo-900">
                                <p className="flex items-center gap-2 font-semibold"><MousePointerSquareDashed className="size-4" /> Draw a hotspot</p>
                                <p className="mt-1 text-indigo-800/80">Drag on the page to draw an area. Click an area to edit it, drag to move it, and use the corner handle to resize. Delete removes it.</p>
                            </div>
                            <p className="mt-5 text-xs font-semibold uppercase tracking-wider text-slate-500">On this page</p>
                            {onPage.length === 0 ? (
                                <p className="mt-2 text-sm text-slate-500">No hotspots yet.</p>
                            ) : (
                                <ul className="mt-2 space-y-1">
                                    {onPage.map((h) => {
                                        const Icon = ACTION_ICON[h.action] || Link2;
                                        return (
                                            <li key={h.id}>
                                                <button type="button" onClick={() => setSelected(h.id)} className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm text-slate-700 hover:bg-slate-50">
                                                    <Icon className="size-4 text-indigo-500" />
                                                    <span className="min-w-0 flex-1 truncate">{h.label || ACTIONS.find(([v]) => v === h.action)?.[1]}</span>
                                                    <span className="text-xs text-slate-400">{clicks[h.id] || 0} click{clicks[h.id] === 1 ? '' : 's'}</span>
                                                </button>
                                            </li>
                                        );
                                    })}
                                </ul>
                            )}
                            {pagesWith.length > 0 && (
                                <>
                                    <p className="mt-5 text-xs font-semibold uppercase tracking-wider text-slate-500">Pages with hotspots</p>
                                    <div className="mt-2 flex flex-wrap gap-1.5">
                                        {pagesWith.map((p) => (
                                            <button key={p} type="button" onClick={() => setPageNum(p)} className={`rounded-md px-2 py-1 text-xs font-semibold ${p === pageNum ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'}`}>
                                                {p}
                                            </button>
                                        ))}
                                    </div>
                                </>
                            )}
                        </div>
                    )}
                </aside>
            </div>
        </div>
    );
};

export default HotspotEditor;
