// components/ShortcodeBuilder.jsx
import React, { useEffect, useMemo, useState } from 'react';
import {
    ScrollText, GalleryHorizontal, BookOpen, PanelsTopLeft, MousePointerClick,
    Copy, Check, Eye, Crown, Lock, RotateCcw,
} from 'lucide-react';
import { MODES, DISPLAYS, DEFAULT_OPTIONS, buildShortcode, isPro, loadSavedOptions, saveOptions } from '../utils/shortcode';
import { useToast } from './Toast';

const MODE_ICONS = { reader: ScrollText, slider: GalleryHorizontal, flipbook: BookOpen };
const DISPLAY_ICONS = { inline: PanelsTopLeft, lightbox: MousePointerClick };

const SWATCHES = ['#f8fafc', '#e2e8f0', '#1e293b', '#0f172a', '#312e81', '#7c2d12'];

export const SectionTitle = ({ children, aside }) => (
    <div className="flex items-center justify-between mb-2.5">
        <h4 className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">{children}</h4>
        {aside}
    </div>
);

export const ProBadge = () => (
    <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-700">
        <Crown className="size-3" /> Pro
    </span>
);

export const Switch = ({ checked, onChange, disabled, label, hint }) => (
    <label className={`flex items-center justify-between gap-4 py-2.5 ${disabled ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}>
        <span className="min-w-0">
            <span className="block text-sm font-medium text-slate-800">{label}</span>
            {hint && <span className="block text-xs text-slate-500 mt-0.5">{hint}</span>}
        </span>
        <button
            type="button"
            role="switch"
            aria-checked={checked}
            disabled={disabled}
            onClick={() => onChange(!checked)}
            className={`relative inline-flex h-5 w-9 shrink-0 rounded-full transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2 ${checked ? 'bg-indigo-600' : 'bg-slate-300'} ${disabled ? 'cursor-not-allowed' : ''}`}
        >
            <span
                className={`absolute top-0.5 left-0.5 size-4 rounded-full bg-white shadow transition-transform duration-200 ${checked ? 'translate-x-4' : 'translate-x-0'}`}
            />
        </button>
    </label>
);

export const Choice = ({ selected, onClick, icon: Icon, label, description }) => (
    <button
        type="button"
        onClick={onClick}
        aria-pressed={selected}
        className={`group relative flex flex-col items-start gap-2 rounded-xl border p-3 text-left transition-all duration-150 ${selected
            ? 'border-indigo-500 bg-indigo-50/70 ring-1 ring-indigo-500 shadow-sm'
            : 'border-slate-200 bg-white hover:border-slate-300 hover:bg-slate-50'
            }`}
    >
        <span className={`rounded-lg p-1.5 transition-colors ${selected ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-500 group-hover:text-slate-700'}`}>
            <Icon className="size-4" />
        </span>
        <span>
            <span className={`block text-sm font-semibold ${selected ? 'text-indigo-900' : 'text-slate-800'}`}>{label}</span>
            <span className="block text-[11px] leading-4 text-slate-500 mt-0.5">{description}</span>
        </span>
        {selected && (
            <span className="absolute top-2.5 right-2.5 rounded-full bg-indigo-600 p-0.5 text-white">
                <Check className="size-2.5" strokeWidth={3} />
            </span>
        )}
    </button>
);

const TextField = ({ label, value, onChange, placeholder, presets = [] }) => (
    <div>
        <label className="block text-xs font-medium text-slate-600 mb-1.5">{label}</label>
        <input
            type="text"
            value={value}
            placeholder={placeholder}
            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 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500"
        />
        {presets.length > 0 && (
            <div className="flex flex-wrap gap-1 mt-1.5">
                {presets.map((p) => (
                    <button
                        key={p}
                        type="button"
                        onClick={() => onChange(p)}
                        className={`px-2 py-0.5 rounded-md text-[11px] font-medium border transition-colors ${value === p ? 'bg-indigo-50 border-indigo-200 text-indigo-700' : 'bg-slate-50 border-slate-200 text-slate-500 hover:text-slate-700'}`}
                    >
                        {p}
                    </button>
                ))}
            </div>
        )}
    </div>
);

/**
 * Pick a viewer mode, display and options, and get a ready-to-paste shortcode.
 *
 * @param {object}   props.pdf        PDF from the REST API ({ id, title, ... })
 * @param {function} props.onPreview  Called with the current options to open a live preview
 */
const ShortcodeBuilder = ({ pdf, onPreview }) => {
    const pro = isPro();
    const { copy } = useToast();
    const [options, setOptions] = useState(loadSavedOptions);
    const [format, setFormat] = useState('shortcode');
    const [copied, setCopied] = useState(false);

    useEffect(() => saveOptions(options), [options]);

    const set = (patch) => setOptions((o) => ({ ...o, ...patch }));

    const shortcode = useMemo(() => buildShortcode(pdf.id, options), [pdf.id, options]);
    const output = format === 'php'
        ? `<?php echo do_shortcode( '${shortcode.replace(/'/g, "\\'")}' ); ?>`
        : shortcode;

    const handleCopy = async () => {
        if (await copy(output, format === 'php' ? 'PHP snippet copied' : 'Shortcode copied')) {
            setCopied(true);
            window.setTimeout(() => setCopied(false), 1800);
        }
    };

    const isDefault = JSON.stringify(options) === JSON.stringify(DEFAULT_OPTIONS);
    const supportsRtl = options.mode !== 'reader';

    return (
        <div className="flex flex-col h-full min-h-0">
            <div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-6">
                {/* Viewer mode */}
                <section>
                    <SectionTitle
                        aside={!isDefault && (
                            <button
                                type="button"
                                onClick={() => setOptions({ ...DEFAULT_OPTIONS })}
                                className="inline-flex items-center gap-1 text-[11px] font-medium text-slate-500 hover:text-indigo-600"
                            >
                                <RotateCcw className="size-3" /> Reset
                            </button>
                        )}
                    >
                        Viewer
                    </SectionTitle>
                    <div className="grid grid-cols-3 gap-2">
                        {MODES.map((m) => (
                            <Choice
                                key={m.value}
                                selected={options.mode === m.value}
                                onClick={() => set({ mode: m.value })}
                                icon={MODE_ICONS[m.value]}
                                label={m.label}
                                description={m.description}
                            />
                        ))}
                    </div>
                </section>

                {/* Display */}
                <section>
                    <SectionTitle>Display</SectionTitle>
                    <div className="grid grid-cols-2 gap-2">
                        {DISPLAYS.map((d) => (
                            <Choice
                                key={d.value}
                                selected={options.display === d.value}
                                onClick={() => set({ display: d.value })}
                                icon={DISPLAY_ICONS[d.value]}
                                label={d.label}
                                description={d.description}
                            />
                        ))}
                    </div>

                    <div className="mt-3 rounded-xl bg-slate-50 border border-slate-100 p-3">
                        {options.display === 'inline' ? (
                            <div className="grid grid-cols-2 gap-3">
                                <TextField
                                    label="Width"
                                    value={options.width}
                                    placeholder="100%"
                                    onChange={(width) => set({ width })}
                                    presets={['100%', '800px']}
                                />
                                <TextField
                                    label="Height"
                                    value={options.height}
                                    placeholder="90vh"
                                    onChange={(height) => set({ height })}
                                    presets={['90vh', '600px', '100vh']}
                                />
                            </div>
                        ) : (
                            <TextField
                                label="Button text"
                                value={options.buttonText}
                                placeholder="View PDF"
                                onChange={(buttonText) => set({ buttonText })}
                                presets={['View PDF', 'Read online', 'Open catalogue']}
                            />
                        )}
                    </div>
                </section>

                {/* Pro options */}
                <section>
                    <SectionTitle aside={<ProBadge />}>Customize</SectionTitle>

                    {!pro && (
                        <div className="mb-2 flex items-start gap-3 rounded-xl border border-amber-200 bg-gradient-to-br from-amber-50 to-white p-3">
                            <Lock className="size-4 mt-0.5 text-amber-600 shrink-0" />
                            <div className="text-xs text-amber-900">
                                <p className="font-semibold">Unlock with PDF Rack Pro</p>
                                <p className="mt-0.5 text-amber-800/80">Hardcover flipbooks, coverflow, right-to-left, brand backgrounds and download/print controls.</p>
                                {window.pdfRack?.upgradeUrl && (
                                    <a href={window.pdfRack.upgradeUrl} className="inline-block mt-1.5 font-semibold text-amber-700 underline underline-offset-2 hover:text-amber-900">
                                        Upgrade now →
                                    </a>
                                )}
                            </div>
                        </div>
                    )}

                    <div className="divide-y divide-slate-100 rounded-xl border border-slate-200 bg-white px-3.5">
                        {options.mode === 'flipbook' && (
                            <Switch
                                label="Hardcover"
                                hint="Rigid first and last pages"
                                checked={pro ? options.cover : false}
                                disabled={!pro}
                                onChange={(cover) => set({ cover })}
                            />
                        )}
                        {options.mode === 'slider' && (
                            <Switch
                                label="Coverflow"
                                hint="3D carousel effect"
                                checked={pro && options.coverflow}
                                disabled={!pro}
                                onChange={(coverflow) => set({ coverflow })}
                            />
                        )}
                        {supportsRtl && (
                            <Switch
                                label="Right-to-left"
                                hint="Turn pages from right to left"
                                checked={pro && options.rtl}
                                disabled={!pro}
                                onChange={(rtl) => set({ rtl })}
                            />
                        )}
                        <div className="py-2.5">
                            <span className="block text-sm font-medium text-slate-800">Toolbar</span>
                            <span className="block text-xs text-slate-500 mt-0.5">
                                {{ visible: 'Always shown.', autohide: 'Fades out while reading; comes back when the reader moves the mouse or taps.', minimize: 'Shrinks to a small page counter while reading; expands on hover or tap.' }[options.toolbar || 'visible']}
                            </span>
                            <div className="mt-2 inline-flex rounded-lg bg-slate-100 p-0.5" role="radiogroup" aria-label="Toolbar">
                                {[['visible', 'Always'], ['autohide', 'Auto-hide'], ['minimize', 'Minimize']].map(([value, label]) => (
                                    <button
                                        key={value}
                                        type="button"
                                        role="radio"
                                        aria-checked={(options.toolbar || 'visible') === value}
                                        onClick={() => set({ toolbar: value })}
                                        className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${(options.toolbar || 'visible') === value ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-800'}`}
                                    >
                                        {label}
                                    </button>
                                ))}
                            </div>
                        </div>
                        <Switch
                            label="Search button"
                            hint="Ctrl/Cmd+F works either way"
                            checked={options.search !== false}
                            onChange={(search) => set({ search })}
                        />
                        <Switch
                            label="Share button"
                            hint="Copy a link to the current page, email and social"
                            checked={options.share !== false}
                            onChange={(share) => set({ share })}
                        />
                        <Switch
                            label="Download button"
                            checked={pro ? options.download : true}
                            disabled={!pro}
                            onChange={(download) => set({ download })}
                        />
                        <Switch
                            label="Watermark"
                            hint="Uses the text from Settings"
                            checked={pro ? options.watermark !== false : false}
                            disabled={!pro}
                            onChange={(watermark) => set({ watermark })}
                        />
                        <Switch
                            label="Print button"
                            checked={pro ? options.print : true}
                            disabled={!pro}
                            onChange={(print) => set({ print })}
                        />
                        <div className={`py-2.5 ${!pro ? 'opacity-60' : ''}`}>
                            <span className="block text-sm font-medium text-slate-800">Background</span>
                            <div className="flex items-center gap-1.5 mt-2">
                                <button
                                    type="button"
                                    disabled={!pro}
                                    onClick={() => set({ background: '' })}
                                    title="Default"
                                    className={`size-7 rounded-lg border text-[10px] font-semibold text-slate-400 bg-[linear-gradient(45deg,#f1f5f9_25%,transparent_25%,transparent_75%,#f1f5f9_75%),linear-gradient(45deg,#f1f5f9_25%,transparent_25%,transparent_75%,#f1f5f9_75%)] [background-size:8px_8px] [background-position:0_0,4px_4px] ${!options.background ? 'ring-2 ring-indigo-500 ring-offset-1 border-transparent' : 'border-slate-200'} disabled:cursor-not-allowed`}
                                >
                                    A
                                </button>
                                {SWATCHES.map((c) => (
                                    <button
                                        key={c}
                                        type="button"
                                        disabled={!pro}
                                        onClick={() => set({ background: c })}
                                        title={c}
                                        style={{ backgroundColor: c }}
                                        className={`size-7 rounded-lg border border-black/10 disabled:cursor-not-allowed ${pro && options.background === c ? 'ring-2 ring-indigo-500 ring-offset-1' : ''}`}
                                    />
                                ))}
                                <label className={`relative size-7 rounded-lg border border-dashed border-slate-300 flex items-center justify-center text-slate-400 text-sm ${pro ? 'cursor-pointer hover:border-indigo-400 hover:text-indigo-500' : 'cursor-not-allowed'}`} title="Custom color">
                                    +
                                    <input
                                        type="color"
                                        disabled={!pro}
                                        value={options.background || '#1e293b'}
                                        onChange={(e) => set({ background: e.target.value })}
                                        className="absolute inset-0 opacity-0 cursor-pointer disabled:cursor-not-allowed"
                                        style={{ padding: 0, border: 0 }}
                                    />
                                </label>
                                {pro && options.background && !SWATCHES.includes(options.background) && (
                                    <span className="ml-1 text-xs font-mono text-slate-500">{options.background}</span>
                                )}
                            </div>
                        </div>
                    </div>
                </section>
            </div>

            {/* Output */}
            <div className="shrink-0 border-t border-slate-200 bg-white px-6 py-4 space-y-3">
                <div className="flex items-center justify-between">
                    <div className="inline-flex rounded-lg bg-slate-100 p-0.5 text-xs font-medium">
                        {[['shortcode', 'Shortcode'], ['php', 'PHP']].map(([value, label]) => (
                            <button
                                key={value}
                                type="button"
                                onClick={() => setFormat(value)}
                                className={`px-2.5 py-1 rounded-md transition-colors ${format === value ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
                            >
                                {label}
                            </button>
                        ))}
                    </div>
                    <span className="text-[11px] text-slate-400">Paste into any post, page or widget</span>
                </div>

                <button
                    type="button"
                    onClick={handleCopy}
                    title="Click to copy"
                    className="group block w-full text-left rounded-xl bg-slate-900 px-4 py-3 font-mono text-[13px] leading-5 text-emerald-300 ring-1 ring-slate-900 hover:ring-indigo-400 transition-shadow break-all"
                >
                    {output}
                </button>

                <div className="flex gap-2">
                    {onPreview && (
                        <button
                            type="button"
                            onClick={() => onPreview(options)}
                            className="flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border border-slate-200 bg-white text-sm font-medium text-slate-700 hover:bg-slate-50 hover:border-slate-300 transition-colors"
                        >
                            <Eye className="size-4" />
                            Preview
                        </button>
                    )}
                    <button
                        type="button"
                        onClick={handleCopy}
                        className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-semibold shadow-sm transition-colors ${copied ? 'bg-emerald-600 text-white' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}
                    >
                        {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
                        {copied ? 'Copied!' : `Copy ${format === 'php' ? 'PHP' : 'shortcode'}`}
                    </button>
                </div>
            </div>
        </div>
    );
};

export default ShortcodeBuilder;
