// components/SettingsPage.jsx
import React, { useEffect, useRef, useState } from 'react';
import { Droplets, BarChart3, Mail, Save, Volume2, Play } from 'lucide-react';
import { playPageTurn } from '../frontend/audio';
import { fetchSettings, saveSettings, sendTestReport } from '../api/pdfs';
import { isPro } from '../utils/shortcode';
import { useToast } from './Toast';
import ProGate from './ProGate';
import BrandingCard, { BRAND_DEFAULTS } from './BrandingCard';

const DEFAULTS = {
    watermark: { enabled: false, text: '{site}', opacity: 0.14, size: 'medium', color: '#0f172a', layout: 'tiled', files: true },
    analytics: { enabled: true, exclude_admins: true, retention_days: 365, weekly_email: false, email_to: '' },
    audio: { flip_sound: false, volume: 0.6 },
    brand: BRAND_DEFAULTS,
    leads: {
        heading: 'Get instant access',
        text: 'Enter your email to keep reading this document.',
        button: 'Continue reading',
        require_name: false,
        consent: '',
        remember_days: 30,
    },
};

const inputClass = 'block w-full px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500';

const Field = ({ id, label, hint, children }) => (
    <div>
        <label className="block text-sm font-medium text-slate-800 mb-1.5" htmlFor={id}>{label}</label>
        {children}
        {hint && <p className="mt-1 text-xs text-slate-500">{hint}</p>}
    </div>
);

const PLACEHOLDERS = [
    ['{site}', 'Site name'],
    ['{url}', 'Domain'],
    ['{user}', 'Viewer name'],
    ['{email}', 'Viewer email'],
    ['{date}', 'Today'],
];

const previewText = (text) => text
    .replaceAll('{site}', window.pdfRack?.siteName || 'My Site')
    .replaceAll('{url}', window.location.hostname)
    .replaceAll('{user}', window.pdfRack?.userName || 'Jane Reader')
    .replaceAll('{email}', 'jane@example.com')
    .replaceAll('{date}', new Date().toLocaleDateString());

/** Same drawing as the viewer's paintWatermark(), on a mock page. */
const WatermarkPreview = ({ wm }) => {
    const ref = useRef(null);
    useEffect(() => {
        const canvas = ref.current;
        if (!canvas) return;
        const dpr = window.devicePixelRatio || 1;
        const w = 220;
        const h = 300;
        canvas.width = w * dpr;
        canvas.height = h * dpr;
        const ctx = canvas.getContext('2d');
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        // mock page
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, w, h);
        ctx.fillStyle = '#6366f1';
        ctx.fillRect(18, 22, 90, 9);
        ctx.fillStyle = '#e2e8f0';
        [0.9, 0.8, 0.86, 0.6].forEach((f, i) => ctx.fillRect(18, 44 + i * 12, (w - 36) * f, 5));
        ctx.fillStyle = '#eef2ff';
        ctx.fillRect(18, 100, w - 36, 70);
        [0.92, 0.84, 0.9, 0.7, 0.86, 0.5].forEach((f, i) => ctx.fillRect(18, 186 + i * 12, (w - 36) * f, 5));

        const text = previewText(wm.text || '').trim();
        if (!wm.enabled || !text) return;
        ctx.save();
        ctx.globalAlpha = wm.opacity;
        ctx.fillStyle = wm.color;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        const family = 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif';
        const angle = -Math.PI / 6;
        if (wm.layout === 'center') {
            let size = w * 0.12;
            ctx.font = `700 ${size}px ${family}`;
            const measured = ctx.measureText(text).width || 1;
            size = Math.min(size * (Math.hypot(w, h) * 0.7) / measured, h * 0.18);
            ctx.font = `700 ${size}px ${family}`;
            ctx.translate(w / 2, h / 2);
            ctx.rotate(angle);
            ctx.fillText(text, 0, 0);
        } else {
            const size = Math.max(7, w * { small: 0.032, medium: 0.046, large: 0.068 }[wm.size]);
            ctx.font = `600 ${size}px ${family}`;
            const stepX = ctx.measureText(text).width + size * 3;
            const stepY = size * 4.5;
            ctx.translate(w / 2, h / 2);
            ctx.rotate(angle);
            const reach = Math.hypot(w, h) / 2 + stepX;
            let row = 0;
            for (let y = -reach; y <= reach; y += stepY, row++) {
                for (let x = -reach + (row % 2 ? stepX / 2 : 0); x <= reach; x += stepX) ctx.fillText(text, x, y);
            }
        }
        ctx.restore();
    }, [wm]);

    return <canvas ref={ref} className="w-[220px] h-[300px] rounded-md shadow-lg ring-1 ring-slate-900/5" aria-label="Watermark preview" />;
};

const Switch = ({ checked, onChange, label, hint }) => (
    <label className="flex items-start justify-between gap-4 py-3 cursor-pointer">
        <span>
            <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}
            onClick={() => onChange(!checked)}
            className={`relative mt-0.5 inline-flex h-5 w-9 shrink-0 rounded-full transition-colors ${checked ? 'bg-indigo-600' : 'bg-slate-300'}`}
        >
            <span className={`absolute top-0.5 left-0.5 size-4 rounded-full bg-white shadow transition-transform ${checked ? 'translate-x-4' : ''}`} />
        </button>
    </label>
);

const Segmented = ({ value, options, onChange }) => (
    <div className="inline-flex rounded-lg bg-slate-100 p-0.5">
        {options.map(([v, label]) => (
            <button
                key={v}
                type="button"
                onClick={() => onChange(v)}
                className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${value === v ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-500 hover:text-slate-800'}`}
            >
                {label}
            </button>
        ))}
    </div>
);

const Card = ({ icon: Icon, title, description, children }) => (
    <section className="rounded-2xl border border-slate-200 bg-white shadow-sm">
        <header className="flex items-start gap-3 px-6 py-5 border-b border-slate-100">
            <span className="rounded-lg bg-indigo-50 p-2 text-indigo-600"><Icon className="size-5" /></span>
            <div>
                <h2 className="text-base font-semibold text-slate-900">{title}</h2>
                <p className="text-sm text-slate-500">{description}</p>
            </div>
        </header>
        <div className="px-6 py-5">{children}</div>
    </section>
);

const TestReportButton = ({ disabled }) => {
    const { toast } = useToast();
    const [sending, setSending] = useState(false);
    const send = async () => {
        setSending(true);
        try {
            const res = await sendTestReport();
            toast(`Report sent to ${res.data.to.join(', ')}`);
        } catch (err) {
            toast(err.message || 'Could not send the report', { type: 'error' });
        } finally {
            setSending(false);
        }
    };
    return (
        <button
            type="button"
            onClick={send}
            disabled={sending || disabled}
            title={disabled ? 'Save your changes first' : undefined}
            className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:border-indigo-300 hover:text-indigo-700 disabled:opacity-50"
        >
            {sending ? 'Sending…' : 'Send a report now'}
        </button>
    );
};

const SettingsForm = ({ settings, setSettings, onSave, saving, dirty }) => {
    const wm = settings.watermark;
    const an = settings.analytics;
    const setWm = (patch) => setSettings((s) => ({ ...s, watermark: { ...s.watermark, ...patch } }));
    const setAn = (patch) => setSettings((s) => ({ ...s, analytics: { ...s.analytics, ...patch } }));
    const ld = { ...DEFAULTS.leads, ...settings.leads };
    const au = { ...DEFAULTS.audio, ...settings.audio };
    const setBrand = (patch) => setSettings((s) => ({ ...s, brand: { ...DEFAULTS.brand, ...s.brand, ...patch } }));
    const setAu = (patch) => setSettings((s) => ({ ...s, audio: { ...DEFAULTS.audio, ...s.audio, ...patch } }));
    const setLd = (patch) => setSettings((s) => ({ ...s, leads: { ...DEFAULTS.leads, ...s.leads, ...patch } }));

    return (
        <div className="space-y-5">
            <BrandingCard Card={Card} Switch={Switch} brand={settings.brand} setBrand={setBrand} />

            <Card icon={Droplets} title="Watermark" description="Stamp a text watermark on every page shown in the viewer.">
                <div className="grid md:grid-cols-[1fr_auto] gap-8">
                    <div className="divide-y divide-slate-100">
                        <Switch label="Enable watermark" hint="Applies to all embeds. Turn it off for one embed with watermark=&quot;false&quot;." checked={wm.enabled} onChange={(enabled) => setWm({ enabled })} />
                        <div className={`py-4 space-y-4 ${wm.enabled ? '' : 'opacity-50 pointer-events-none'}`}>
                            <div>
                                <label className="block text-sm font-medium text-slate-800 mb-1.5" htmlFor="wm-text">Text</label>
                                <input
                                    id="wm-text"
                                    type="text"
                                    value={wm.text}
                                    onChange={(e) => setWm({ text: e.target.value })}
                                    className="block w-full px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500"
                                />
                                <div className="flex flex-wrap gap-1.5 mt-2">
                                    {PLACEHOLDERS.map(([token, label]) => (
                                        <button
                                            key={token}
                                            type="button"
                                            title={label}
                                            onClick={() => setWm({ text: `${wm.text}${wm.text && !wm.text.endsWith(' ') ? ' ' : ''}${token}` })}
                                            className="px-2 py-0.5 rounded-md bg-slate-50 border border-slate-200 text-[11px] font-mono text-slate-600 hover:border-indigo-300 hover:text-indigo-700"
                                        >
                                            {token}
                                        </button>
                                    ))}
                                </div>
                            </div>
                            <div className="flex flex-wrap items-center gap-x-6 gap-y-3">
                                <div>
                                    <span className="block text-xs font-medium text-slate-600 mb-1.5">Layout</span>
                                    <Segmented value={wm.layout} onChange={(layout) => setWm({ layout })} options={[['tiled', 'Tiled'], ['center', 'Centered']]} />
                                </div>
                                {wm.layout === 'tiled' && (
                                    <div>
                                        <span className="block text-xs font-medium text-slate-600 mb-1.5">Size</span>
                                        <Segmented value={wm.size} onChange={(size) => setWm({ size })} options={[['small', 'S'], ['medium', 'M'], ['large', 'L']]} />
                                    </div>
                                )}
                                <div>
                                    <span className="block text-xs font-medium text-slate-600 mb-1.5">Color</span>
                                    <input type="color" value={wm.color} onChange={(e) => setWm({ color: e.target.value })} className="h-8 w-12 cursor-pointer rounded-md border border-slate-200 bg-white p-0.5" style={{ padding: 2 }} />
                                </div>
                            </div>
                            <div>
                                <label className="flex items-center justify-between text-xs font-medium text-slate-600 mb-1.5" htmlFor="wm-opacity">
                                    Opacity <span className="tabular-nums text-slate-500">{Math.round(wm.opacity * 100)}%</span>
                                </label>
                                <input id="wm-opacity" type="range" min="0.03" max="0.6" step="0.01" value={wm.opacity} onChange={(e) => setWm({ opacity: Number(e.target.value) })} className="w-full accent-indigo-600" style={{ padding: 0, border: 0, boxShadow: 'none' }} />
                            </div>
                            <div className="-mx-0 border-t border-slate-100">
                                <Switch
                                    label="Watermark downloads and prints"
                                    hint="Download and Print hand out a copy with the same watermark, prepared in the reader's browser. Turn off to give the original file."
                                    checked={wm.files !== false}
                                    onChange={(files) => setWm({ files })}
                                />
                            </div>
                            <p className="text-xs leading-relaxed text-slate-500">
                                A watermark discourages sharing but is not copy protection. For sensitive documents, also hide the download and print buttons, or protect the PDF with a password so its address stays private.
                            </p>
                        </div>
                    </div>
                    <div className="flex flex-col items-center gap-2 rounded-xl bg-slate-100 p-5">
                        <WatermarkPreview wm={wm} />
                        <span className="text-[11px] text-slate-500">Preview</span>
                    </div>
                </div>
            </Card>

            <Card icon={BarChart3} title="Analytics" description="Track how your embedded PDFs are read.">
                <div className="divide-y divide-slate-100">
                    <Switch label="Collect reading analytics" hint="Views, reading time, pages read, downloads and prints. No IP addresses are stored." checked={an.enabled} onChange={(enabled) => setAn({ enabled })} />
                    <Switch label="Ignore administrators" hint="Don't count views by users who can manage the site." checked={an.exclude_admins} onChange={(exclude_admins) => setAn({ exclude_admins })} />
                    <div className="flex items-center justify-between gap-4 py-3">
                        <span>
                            <span className="block text-sm font-medium text-slate-800">Keep data for</span>
                            <span className="block text-xs text-slate-500 mt-0.5">Older reading sessions are deleted automatically.</span>
                        </span>
                        <select
                            value={an.retention_days}
                            onChange={(e) => setAn({ retention_days: Number(e.target.value) })}
                            className="w-36 px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm"
                        >
                            {[[30, '30 days'], [90, '90 days'], [180, '6 months'], [365, '1 year'], [730, '2 years']].map(([v, l]) => (
                                <option key={v} value={v}>{l}</option>
                            ))}
                        </select>
                    </div>
                    <Switch label="Weekly email report" hint="Every Monday morning: views, visitors, reading time and the most-read PDFs of the past week." checked={!!an.weekly_email} onChange={(weekly_email) => setAn({ weekly_email })} />
                    {an.weekly_email && (
                        <div className="py-3 space-y-2">
                            <label className="block">
                                <span className="block text-sm font-medium text-slate-800">Send to</span>
                                <span className="block text-xs text-slate-500 mt-0.5">Comma separated. Leave empty for the site admin email.</span>
                                <input
                                    type="text"
                                    value={an.email_to || ''}
                                    onChange={(e) => setAn({ email_to: e.target.value })}
                                    placeholder={window.pdfRack?.adminEmail || 'you@example.com'}
                                    className="mt-1.5 block w-full px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm"
                                />
                            </label>
                            <TestReportButton disabled={dirty} />
                        </div>
                    )}
                </div>
            </Card>

            <Card icon={Volume2} title="Sound" description="Page-turn sound for the flipbook and slider. Background audio is chosen per PDF in its details.">
                <div className="divide-y divide-slate-100">
                    <Switch label="Page-turn sound" hint="A soft paper sound on every page turn. Turn it off for one embed with sound=&quot;false&quot;." checked={!!au.flip_sound} onChange={(flip_sound) => setAu({ flip_sound })} />
                    <div className={`flex items-center gap-4 py-3 ${au.flip_sound ? '' : 'opacity-50 pointer-events-none'}`}>
                        <span className="text-sm font-medium text-slate-800 w-16">Volume</span>
                        <input type="range" min="0.05" max="1" step="0.05" value={au.volume} onChange={(e) => setAu({ volume: Number(e.target.value) })} className="flex-1 accent-indigo-600" style={{ padding: 0, border: 0, boxShadow: 'none' }} aria-label="Page-turn volume" />
                        <button type="button" onClick={() => playPageTurn(au.volume)} className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:border-indigo-300 hover:text-indigo-700">
                            <Play className="size-3.5" /> Preview
                        </button>
                    </div>
                </div>
            </Card>

            <Card icon={Mail} title="Lead capture form" description="The sign-up form shown on PDFs with lead capture turned on (set per PDF in its details).">
                <div className="space-y-4">
                    <Field id="ld-heading" label="Heading">
                        <input id="ld-heading" type="text" value={ld.heading} onChange={(e) => setLd({ heading: e.target.value })} className={inputClass} />
                    </Field>
                    <Field id="ld-text" label="Message">
                        <textarea id="ld-text" rows={2} value={ld.text} onChange={(e) => setLd({ text: e.target.value })} className={inputClass} />
                    </Field>
                    <Field id="ld-button" label="Button label">
                        <input id="ld-button" type="text" value={ld.button} onChange={(e) => setLd({ button: e.target.value })} className={inputClass} />
                    </Field>
                    <Field id="ld-consent" label="Consent checkbox" hint={<>Leave empty for no checkbox. Links are allowed, e.g. <code className="font-mono">&lt;a href="/privacy"&gt;privacy policy&lt;/a&gt;</code>.</>}>
                        <input id="ld-consent" type="text" value={ld.consent} placeholder="I agree to receive emails and accept the privacy policy." onChange={(e) => setLd({ consent: e.target.value })} className={inputClass} />
                    </Field>
                    <div className="divide-y divide-slate-100 border-t border-slate-100">
                        <Switch label="Require a name" hint="Otherwise the name field is optional." checked={!!ld.require_name} onChange={(require_name) => setLd({ require_name })} />
                        <div className="flex items-center justify-between gap-4 py-3">
                            <span>
                                <span className="block text-sm font-medium text-slate-800">Remember visitors for</span>
                                <span className="block text-xs text-slate-500 mt-0.5">A visitor who signed up isn't asked again on this browser until then.</span>
                            </span>
                            <select value={ld.remember_days} onChange={(e) => setLd({ remember_days: Number(e.target.value) })} className="w-36 px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm">
                                {[[1, '1 day'], [7, '7 days'], [30, '30 days'], [90, '90 days'], [365, '1 year']].map(([v, l]) => (
                                    <option key={v} value={v}>{l}</option>
                                ))}
                            </select>
                        </div>
                    </div>
                </div>
            </Card>

            <div className="sticky bottom-4 flex justify-end">
                <button
                    onClick={onSave}
                    disabled={saving || !dirty}
                    className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white text-sm font-semibold rounded-lg shadow-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    {saving ? <span className="size-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save className="size-4" />}
                    {saving ? 'Saving…' : dirty ? 'Save settings' : 'Saved'}
                </button>
            </div>
        </div>
    );
};

const SettingsPage = () => {
    const { toast } = useToast();
    const pro = isPro();
    const [settings, setSettings] = useState(DEFAULTS);
    const [saved, setSaved] = useState(null);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        if (!pro) return;
        fetchSettings()
            .then((res) => {
                setSettings(res.data);
                setSaved(JSON.stringify(res.data));
            })
            .catch((err) => toast(err.message || 'Could not load settings', { type: 'error' }));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pro]);

    const handleSave = async () => {
        setSaving(true);
        try {
            const res = await saveSettings(settings);
            setSettings(res.data);
            setSaved(JSON.stringify(res.data));
            toast('Settings saved');
        } catch (err) {
            toast(err.message || 'Could not save settings', { type: 'error' });
        } finally {
            setSaving(false);
        }
    };

    if (!pro) {
        return (
            <ProGate
                title="Protect and track your documents"
                description="Watermarks and reading analytics are part of PDF Rack Pro."
                features={['Your colours, toolbar style and logo on every viewer', 'Text watermark with your site name, viewer or date', 'Privacy-friendly reading analytics', 'Password-protect individual PDFs', 'Collect emails before or during reading']}
            >
                <SettingsForm settings={{ ...DEFAULTS, watermark: { ...DEFAULTS.watermark, enabled: true } }} setSettings={() => {}} onSave={() => {}} />
            </ProGate>
        );
    }

    return (
        <SettingsForm
            settings={settings}
            setSettings={setSettings}
            onSave={handleSave}
            saving={saving}
            dirty={saved !== null && JSON.stringify(settings) !== saved}
        />
    );
};

export default SettingsPage;
