// components/ShelfDrawer.jsx
import React, { useEffect, useMemo, useState } from 'react';
import { X, Library, LayoutGrid, BookOpen, GalleryHorizontal, List, Copy, Check, FileText } from 'lucide-react';
import { MODES, isPro } from '../utils/shortcode';
import { useToast } from './Toast';
import { SectionTitle, ProBadge, Switch, Choice } from './ShortcodeBuilder';

// Mirrors Shelf::defaults() in includes/Frontend/Shelf.php.
const DEFAULTS = {
    category: '',
    tag: '',
    orderby: 'date',
    order: 'desc',
    limit: 24,
    columns: 4,
    mode: 'flipbook',
    style: 'grid',
    search: false,
    titles: true,
};

const STYLES = [
    { value: 'grid', label: 'Cover grid', description: 'Responsive covers', icon: LayoutGrid },
    { value: 'shelf', label: 'Bookshelf', description: 'Books on wooden shelves', icon: BookOpen, pro: true },
    { value: 'carousel', label: 'Carousel', description: 'One swipeable row', icon: GalleryHorizontal, pro: true },
    { value: 'list', label: 'List', description: 'Covers with descriptions', icon: List, pro: true },
];

const STORAGE_KEY = 'pdfrack-shelf-options';

const load = () => {
    try {
        return { ...DEFAULTS, ...JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '{}') };
    } catch {
        return { ...DEFAULTS };
    }
};

export const buildShelfShortcode = (o, pro = isPro()) => {
    const attrs = [];
    if (o.category) attrs.push(`category="${o.category}"`);
    if (o.tag) attrs.push(`tag="${o.tag}"`);
    if (o.orderby !== DEFAULTS.orderby) attrs.push(`orderby="${o.orderby}"`);
    if (o.order !== DEFAULTS.order && o.orderby !== 'random') attrs.push(`order="${o.order}"`);
    if (o.limit !== DEFAULTS.limit) attrs.push(`limit="${o.limit}"`);
    if (o.columns !== DEFAULTS.columns && o.style !== 'list') attrs.push(`columns="${o.columns}"`);
    if (o.mode !== DEFAULTS.mode) attrs.push(`mode="${o.mode}"`);
    if (!o.titles && o.style !== 'list') attrs.push('titles="false"');
    if (pro && o.style !== 'grid') attrs.push(`style="${o.style}"`);
    if (pro && o.search) attrs.push('search="true"');
    return `[pdf-rack-shelf${attrs.length ? ' ' + attrs.join(' ') : ''}]`;
};

const Select = ({ label, value, onChange, children }) => (
    <label className="block">
        <span className="block text-xs font-medium text-slate-600 mb-1.5">{label}</span>
        <select
            value={value}
            onChange={(e) => onChange(e.target.value)}
            className="block w-full px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm text-slate-900"
        >
            {children}
        </select>
    </label>
);

/** Rough picture of the chosen style using the library's own covers. */
const Preview = ({ pdfs, options }) => {
    const items = pdfs.slice(0, options.style === 'list' ? 3 : Math.min(8, options.columns * 2));
    const cover = (pdf, extra = '') => (
        <span className={`block aspect-[3/4] overflow-hidden rounded-[3px] bg-indigo-50 shadow-md ${extra}`}>
            {pdf.thumbnail
                ? <img src={pdf.thumbnail} alt="" className="size-full object-cover object-top" />
                : <span className="flex size-full items-center justify-center text-indigo-300"><FileText className="size-5" /></span>}
        </span>
    );

    if (!items.length) {
        return <p className="py-6 text-center text-xs text-slate-500">No PDFs match these filters.</p>;
    }
    if (options.style === 'list') {
        return (
            <div className="space-y-2">
                {items.map((pdf) => (
                    <div key={pdf.id} className="flex items-center gap-3 rounded-lg border border-slate-200 bg-white p-2">
                        <span className="w-9 shrink-0">{cover(pdf)}</span>
                        <span className="min-w-0">
                            <span className="block truncate text-xs font-semibold text-slate-800">{pdf.title || pdf.name}</span>
                            <span className="mt-1 inline-block rounded bg-indigo-600 px-1.5 py-0.5 text-[9px] font-semibold text-white">Read</span>
                        </span>
                    </div>
                ))}
            </div>
        );
    }

    const cols = options.style === 'carousel' ? Math.min(options.columns, 4) : Math.min(options.columns, 6);
    const grid = (
        <div
            className={options.style === 'carousel' ? 'grid gap-3 overflow-hidden' : 'grid gap-x-3 gap-y-5'}
            style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))` }}
        >
            {(options.style === 'carousel' ? items.slice(0, cols) : items).map((pdf) => (
                <div key={pdf.id} className={options.style === 'shelf' ? 'relative pb-2' : ''}>
                    {cover(pdf)}
                    {options.style === 'shelf' && <span className="absolute -left-2 -right-2 bottom-0 h-2 bg-gradient-to-b from-[#b07a47] to-[#6b4424]" />}
                    {options.titles && options.style !== 'shelf' && (
                        <span className="mt-1.5 block truncate text-[10px] font-medium text-slate-700">{pdf.title || pdf.name}</span>
                    )}
                </div>
            ))}
        </div>
    );
    if (options.style === 'shelf') {
        return <div className="overflow-hidden rounded-lg bg-gradient-to-b from-[#3b2a1e] to-[#2b1e15] px-3 pt-3 pb-1">{grid}</div>;
    }
    return grid;
};

const ShelfDrawer = ({ open, onClose, pdfs, categories, tags }) => {
    const { copy } = useToast();
    const pro = isPro();
    const [options, setOptions] = useState(load);
    const [copied, setCopied] = useState(false);

    const set = (patch) => setOptions((o) => {
        const next = { ...o, ...patch };
        try {
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
        } catch {
            /* storage unavailable: ignore */
        }
        return next;
    });

    useEffect(() => {
        if (!open) return undefined;
        const onKey = (e) => e.key === 'Escape' && onClose();
        window.addEventListener('keydown', onKey);
        return () => window.removeEventListener('keydown', onKey);
    }, [open, onClose]);

    const shortcode = buildShelfShortcode(options, pro);

    const matching = useMemo(() => {
        let list = pdfs.filter((p) =>
            (!options.category || p.categories?.some((c) => c.slug === options.category))
            && (!options.tag || p.tags?.some((t) => t.slug === options.tag)));
        if (options.orderby === 'title') {
            list = [...list].sort((a, b) => String(a.title || a.name).localeCompare(String(b.title || b.name)));
            if (options.order === 'desc') list.reverse();
        } else if (options.orderby === 'date' && options.order === 'asc') {
            list = [...list].reverse();
        }
        return list.slice(0, options.limit);
    }, [pdfs, options]);

    if (!open) return null;

    const handleCopy = async () => {
        await copy(shortcode, 'Shelf shortcode copied');
        setCopied(true);
        setTimeout(() => setCopied(false), 1500);
    };

    return (
        <div className="fixed inset-0 z-[99990]">
            <div className="absolute inset-0 bg-slate-900/40 backdrop-blur-[2px] animate-fade-in" onClick={onClose} />
            <aside
                className="absolute top-8 bottom-0 right-0 w-full max-w-[480px] bg-white shadow-2xl flex flex-col animate-slide-in-right"
                role="dialog"
                aria-label="Embed a PDF shelf"
            >
                <header className="shrink-0 flex items-center gap-3 px-6 py-4 border-b border-slate-200">
                    <span className="size-11 shrink-0 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center">
                        <Library className="size-5" />
                    </span>
                    <div className="min-w-0 flex-1">
                        <p className="text-[11px] font-semibold uppercase tracking-wider text-indigo-600">Embed</p>
                        <h2 className="text-base font-semibold text-slate-900">PDF shelf</h2>
                    </div>
                    <button onClick={onClose} className="p-2 text-slate-400 hover:text-slate-900 hover:bg-slate-100 rounded-full transition-colors" aria-label="Close">
                        <X className="size-5" />
                    </button>
                </header>

                <div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-6">
                    <p className="text-sm text-slate-500">
                        Show a set of PDFs as covers on any page. Each cover opens its PDF in a popup viewer. The shelf updates by itself as you add PDFs.
                    </p>

                    <section>
                        <SectionTitle>Style</SectionTitle>
                        <div className="grid grid-cols-2 gap-2">
                            {STYLES.map((s) => (
                                <div key={s.value} className={`relative ${s.pro && !pro ? 'opacity-60' : ''}`}>
                                    <Choice
                                        selected={options.style === s.value}
                                        onClick={() => (pro || !s.pro) && set({ style: s.value })}
                                        icon={s.icon}
                                        label={s.label}
                                        description={s.description}
                                    />
                                    {s.pro && !pro && <span className="absolute top-2.5 right-2.5"><ProBadge /></span>}
                                </div>
                            ))}
                        </div>
                    </section>

                    <section>
                        <SectionTitle>Preview</SectionTitle>
                        <div className="rounded-xl border border-slate-200 bg-slate-50 p-3">
                            <Preview pdfs={matching} options={options} />
                        </div>
                        <p className="mt-1.5 text-[11px] text-slate-400">
                            {matching.length} PDF{matching.length === 1 ? '' : 's'} · the live shelf adapts to your theme and screen size.
                        </p>
                    </section>

                    <section>
                        <SectionTitle>Documents</SectionTitle>
                        <div className="grid grid-cols-2 gap-3">
                            <Select label="Category" value={options.category} onChange={(category) => set({ category })}>
                                <option value="">All categories</option>
                                {categories.map((c) => <option key={c.id} value={c.slug}>{c.name}</option>)}
                            </Select>
                            <Select label="Tag" value={options.tag} onChange={(tag) => set({ tag })}>
                                <option value="">All tags</option>
                                {tags.map((t) => <option key={t.id} value={t.slug}>{t.name}</option>)}
                            </Select>
                            <Select label="Order" value={`${options.orderby}:${options.order}`} onChange={(v) => {
                                const [orderby, order] = v.split(':');
                                set({ orderby, order });
                            }}>
                                <option value="date:desc">Newest first</option>
                                <option value="date:asc">Oldest first</option>
                                <option value="title:asc">Title A → Z</option>
                                <option value="title:desc">Title Z → A</option>
                                <option value="random:desc">Random</option>
                            </Select>
                            <label className="block">
                                <span className="block text-xs font-medium text-slate-600 mb-1.5">Maximum</span>
                                <input
                                    type="number"
                                    min="1"
                                    max="200"
                                    value={options.limit}
                                    onChange={(e) => set({ limit: Math.max(1, Math.min(200, Number(e.target.value) || 1)) })}
                                    className="block w-full px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm text-slate-900"
                                />
                            </label>
                        </div>
                    </section>

                    <section>
                        <SectionTitle>Layout</SectionTitle>
                        <div className="divide-y divide-slate-100 rounded-xl border border-slate-200 bg-white px-3.5">
                            {options.style !== 'list' && (
                                <div className="py-2.5">
                                    <span className="flex items-center justify-between text-sm font-medium text-slate-800">
                                        Columns <span className="tabular-nums text-slate-500">{options.columns}</span>
                                    </span>
                                    <input
                                        type="range"
                                        min="1"
                                        max="8"
                                        value={options.columns}
                                        onChange={(e) => set({ columns: Number(e.target.value) })}
                                        className="mt-2 w-full accent-indigo-600"
                                        style={{ padding: 0, border: 0, boxShadow: 'none' }}
                                    />
                                    <span className="block text-xs text-slate-500">Fewer columns are used on small screens.</span>
                                </div>
                            )}
                            {options.style !== 'list' && (
                                <Switch label="Show titles" checked={options.titles} onChange={(titles) => set({ titles })} />
                            )}
                            <Switch
                                label={<span className="inline-flex items-center gap-2">Search &amp; category filter {!pro && <ProBadge />}</span>}
                                hint="A search box and category chips above the shelf"
                                checked={pro && options.search}
                                disabled={!pro}
                                onChange={(search) => set({ search })}
                            />
                            <div className="py-2.5">
                                <span className="block text-sm font-medium text-slate-800 mb-2">Open PDFs in</span>
                                <div className="inline-flex rounded-lg bg-slate-100 p-0.5">
                                    {MODES.map((m) => (
                                        <button
                                            key={m.value}
                                            type="button"
                                            onClick={() => set({ mode: m.value })}
                                            className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${options.mode === m.value ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-800'}`}
                                        >
                                            {m.label}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </section>
                </div>

                <footer className="shrink-0 border-t border-slate-200 bg-slate-50 px-6 py-4">
                    <div className="flex items-center gap-2">
                        <code className="flex-1 min-w-0 truncate rounded-lg bg-slate-900 px-3 py-2.5 font-mono text-xs text-emerald-300" title={shortcode}>
                            {shortcode}
                        </code>
                        <button
                            type="button"
                            onClick={handleCopy}
                            className="inline-flex items-center gap-1.5 shrink-0 px-3.5 py-2.5 bg-indigo-600 text-white text-sm font-semibold rounded-lg hover:bg-indigo-700"
                        >
                            {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
                            {copied ? 'Copied' : 'Copy'}
                        </button>
                    </div>
                    <p className="mt-2 text-[11px] text-slate-500">Paste it into any page, or add the <strong className="font-semibold text-slate-700">PDF Rack Shelf</strong> block in the editor.</p>
                </footer>
            </aside>
        </div>
    );
};

export default ShelfDrawer;
