// components/AnalyticsPage.jsx
import React, { useEffect, useMemo, useState } from 'react';
import { Eye, Users, Clock, BookOpenCheck, Download, Printer, ArrowUpRight, ArrowDownRight, Table2, BarChart3, RotateCcw, FileText, Smartphone, Monitor } from 'lucide-react';
import { fetchAnalytics, resetAnalytics, exportAnalytics } from '../api/pdfs';
import PageAttention from './PageAttention';
import { isPro } from '../utils/shortcode';
import { useToast } from './Toast';
import ProGate from './ProGate';

const RANGES = [7, 30, 90];

export const formatDuration = (seconds) => {
    const s = Math.round(seconds || 0);
    if (s < 60) return `${s}s`;
    const m = Math.floor(s / 60);
    if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`;
    return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`;
};

const formatNumber = (n) => new Intl.NumberFormat().format(n || 0);
const formatDay = (iso, opts = { month: 'short', day: 'numeric' }) =>
    new Date(`${iso}T00:00:00`).toLocaleDateString(undefined, opts);

/** Deterministic sample data for the locked (free) preview. */
const sampleData = (days) => {
    const series = Array.from({ length: days }, (_, i) => {
        const d = new Date();
        d.setDate(d.getDate() - (days - 1 - i));
        const views = Math.round(40 + 25 * Math.sin(i / 3) + (i % 7) * 4 + i * 0.8);
        return { date: d.toISOString().slice(0, 10), views, visitors: Math.round(views * 0.7) };
    });
    const views = series.reduce((a, b) => a + b.views, 0);
    return {
        days,
        totals: { views, visitors: Math.round(views * 0.68), avgDuration: 134, downloads: Math.round(views * 0.08), prints: Math.round(views * 0.02), completion: 0.46 },
        previous: { views: Math.round(views * 0.86), visitors: Math.round(views * 0.6), avgDuration: 121, downloads: Math.round(views * 0.07), prints: 9, completion: 0.41 },
        series,
        top: [
            { id: 1, title: 'Product Catalogue 2026', views: 612, visitors: 431, avgDuration: 188, downloads: 52, completion: 0.58 },
            { id: 2, title: 'Annual Report', views: 344, visitors: 280, avgDuration: 241, downloads: 18, completion: 0.37 },
            { id: 3, title: 'Price List', views: 201, visitors: 166, avgDuration: 64, downloads: 31, completion: 0.81 },
        ],
        devices: { desktop: Math.round(views * 0.62), mobile: Math.round(views * 0.38) },
    };
};

const Delta = ({ now, before, invert = false }) => {
    if (!before) return null;
    const change = (now - before) / before;
    if (!Number.isFinite(change) || Math.abs(change) < 0.005) {
        return <span className="text-xs text-slate-400">no change</span>;
    }
    const up = change > 0;
    const good = invert ? !up : up;
    const Icon = up ? ArrowUpRight : ArrowDownRight;
    return (
        <span className={`inline-flex items-center gap-0.5 text-xs font-semibold ${good ? 'text-emerald-600' : 'text-rose-600'}`}>
            <Icon className="size-3.5" aria-hidden="true" />
            {Math.abs(change * 100).toFixed(0)}%
            <span className="sr-only">{up ? 'increase' : 'decrease'} vs previous period</span>
        </span>
    );
};

const StatTile = ({ icon: Icon, label, value, delta }) => (
    <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
        <div className="flex items-center gap-2 text-xs font-medium text-slate-500">
            <Icon className="size-4 text-slate-400" aria-hidden="true" />
            {label}
        </div>
        <div className="mt-2 flex items-end justify-between gap-2">
            <span className="text-2xl font-bold text-slate-900 tabular-nums">{value}</span>
            {delta}
        </div>
    </div>
);

/** Single-series bar chart of daily views with a per-bar tooltip. */
const ViewsChart = ({ series }) => {
    const [hover, setHover] = useState(null);
    const W = 760;
    const H = 220;
    const pad = { top: 12, right: 8, bottom: 26, left: 36 };
    const max = Math.max(4, ...series.map((d) => d.views));
    const niceMax = (() => {
        const step = 10 ** Math.floor(Math.log10(max));
        return Math.ceil(max / step) * step;
    })();
    const ticks = [0, niceMax / 2, niceMax];
    const innerW = W - pad.left - pad.right;
    const innerH = H - pad.top - pad.bottom;
    const slot = innerW / series.length;
    const barW = Math.max(2, Math.min(28, slot - 2)); // 2px gap between bars
    const y = (v) => pad.top + innerH - (v / niceMax) * innerH;
    const labelEvery = Math.ceil(series.length / 8);

    const bar = (d, i) => {
        const x = pad.left + i * slot + (slot - barW) / 2;
        const top = y(d.views);
        const h = pad.top + innerH - top;
        const r = Math.min(4, barW / 2, h);
        // Rounded data end (top), square at the baseline
        const path = h <= 0 ? '' : `M${x},${top + h} V${top + r} Q${x},${top} ${x + r},${top} H${x + barW - r} Q${x + barW},${top} ${x + barW},${top + r} V${top + h} Z`;
        return { x, top, h, path };
    };

    return (
        <div className="relative" onMouseLeave={() => setHover(null)}>
            <svg viewBox={`0 0 ${W} ${H}`} className="w-full h-auto" role="img" aria-label="Daily views">
                {ticks.map((t) => (
                    <g key={t}>
                        <line x1={pad.left} x2={W - pad.right} y1={y(t)} y2={y(t)} stroke="#e2e8f0" strokeWidth="1" />
                        <text x={pad.left - 8} y={y(t)} textAnchor="end" dominantBaseline="middle" fontSize="11" fill="#94a3b8">
                            {formatNumber(t)}
                        </text>
                    </g>
                ))}
                {series.map((d, i) => {
                    const b = bar(d, i);
                    return (
                        <g key={d.date}>
                            {b.path && (
                                <path d={b.path} fill={hover === i ? '#4338ca' : '#6366f1'} />
                            )}
                            {/* Hit target: the whole column, larger than the mark */}
                            <rect
                                x={pad.left + i * slot}
                                y={pad.top}
                                width={slot}
                                height={innerH}
                                fill="transparent"
                                onMouseEnter={() => setHover(i)}
                            />
                            {i % labelEvery === 0 && (
                                <text x={b.x + barW / 2} y={H - 8} textAnchor="middle" fontSize="11" fill="#94a3b8">
                                    {formatDay(d.date)}
                                </text>
                            )}
                        </g>
                    );
                })}
            </svg>
            {hover !== null && series[hover] && (() => {
                const d = series[hover];
                const b = bar(d, hover);
                const left = ((b.x + barW / 2) / W) * 100;
                return (
                    <div
                        className="pointer-events-none absolute -translate-x-1/2 -translate-y-full rounded-lg bg-slate-900 px-3 py-2 text-xs text-white shadow-lg"
                        style={{ left: `${left}%`, top: `${(b.top / H) * 100}%`, marginTop: -8 }}
                    >
                        <div className="font-semibold">{formatDay(d.date, { weekday: 'short', month: 'short', day: 'numeric' })}</div>
                        <div className="mt-0.5 text-slate-300">{formatNumber(d.views)} views · {formatNumber(d.visitors)} visitors</div>
                    </div>
                );
            })()}
        </div>
    );
};

const Dashboard = ({ data, days, setDays, onReset, onExport, loading }) => {
    const [asTable, setAsTable] = useState(false);
    const [selected, setSelected] = useState(null);
    const { totals, previous, series, top, devices } = data;
    const deviceTotal = Number(devices?.desktop || 0) + Number(devices?.mobile || 0);

    return (
        <div className={`space-y-5 transition-opacity ${loading ? 'opacity-60' : ''}`}>
            <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="inline-flex rounded-lg bg-white p-0.5 ring-1 ring-slate-200" role="tablist" aria-label="Date range">
                    {RANGES.map((r) => (
                        <button
                            key={r}
                            role="tab"
                            aria-selected={days === r}
                            onClick={() => setDays(r)}
                            className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${days === r ? 'bg-indigo-600 text-white' : 'text-slate-600 hover:text-slate-900'}`}
                        >
                            Last {r} days
                        </button>
                    ))}
                </div>
                <div className="flex items-center gap-4">
                    {onExport && (
                        <button onClick={onExport} className="inline-flex items-center gap-1.5 text-sm font-medium text-slate-600 hover:text-indigo-700">
                            <Download className="size-4" /> Export CSV
                        </button>
                    )}
                    {onReset && (
                        <button onClick={onReset} className="inline-flex items-center gap-1.5 text-sm font-medium text-slate-500 hover:text-rose-600">
                            <RotateCcw className="size-4" /> Reset data
                        </button>
                    )}
                </div>
            </div>

            <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
                <StatTile icon={Eye} label="Views" value={formatNumber(totals.views)} delta={<Delta now={totals.views} before={previous.views} />} />
                <StatTile icon={Users} label="Unique visitors" value={formatNumber(totals.visitors)} delta={<Delta now={totals.visitors} before={previous.visitors} />} />
                <StatTile icon={Clock} label="Avg. reading time" value={formatDuration(totals.avgDuration)} delta={<Delta now={totals.avgDuration} before={previous.avgDuration} />} />
                <StatTile icon={BookOpenCheck} label="Read-through" value={`${Math.round(totals.completion * 100)}%`} delta={<Delta now={totals.completion} before={previous.completion} />} />
                <StatTile icon={Download} label="Downloads" value={formatNumber(totals.downloads)} delta={<Delta now={totals.downloads} before={previous.downloads} />} />
                <StatTile icon={Printer} label="Prints" value={formatNumber(totals.prints)} delta={<Delta now={totals.prints} before={previous.prints} />} />
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
                <div className="flex items-center justify-between gap-3 mb-3">
                    <div>
                        <h3 className="text-sm font-semibold text-slate-900">Views per day</h3>
                        <p className="text-xs text-slate-500">Each time a PDF is opened in a viewer counts as one view.</p>
                    </div>
                    <button
                        onClick={() => setAsTable((v) => !v)}
                        className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium text-slate-600 ring-1 ring-slate-200 hover:bg-slate-50"
                    >
                        {asTable ? <BarChart3 className="size-3.5" /> : <Table2 className="size-3.5" />}
                        {asTable ? 'Chart' : 'Table'}
                    </button>
                </div>
                {asTable ? (
                    <div className="max-h-72 overflow-auto">
                        <table className="w-full text-sm">
                            <thead className="text-left text-xs text-slate-500">
                                <tr><th className="py-1.5 pr-4 font-medium">Date</th><th className="py-1.5 pr-4 font-medium text-right">Views</th><th className="py-1.5 font-medium text-right">Visitors</th></tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100 text-slate-700 tabular-nums">
                                {[...series].reverse().map((d) => (
                                    <tr key={d.date}><td className="py-1.5 pr-4">{formatDay(d.date, { year: 'numeric', month: 'short', day: 'numeric' })}</td><td className="py-1.5 pr-4 text-right">{d.views}</td><td className="py-1.5 text-right">{d.visitors}</td></tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                ) : (
                    <ViewsChart series={series} />
                )}
            </div>

            <div className="grid lg:grid-cols-3 gap-5">
                <div className="lg:col-span-2 rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                    <div className="px-5 py-4 border-b border-slate-100">
                        <h3 className="text-sm font-semibold text-slate-900">Top PDFs</h3>
                        <p className="text-xs text-slate-500">Click a document to see which pages hold attention.</p>
                    </div>
                    {top.length === 0 ? (
                        <p className="px-5 py-10 text-center text-sm text-slate-500">No views in this period yet.</p>
                    ) : (
                        <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                            <thead className="bg-slate-50 text-left text-xs text-slate-500">
                                <tr>
                                    <th className="px-5 py-2 font-medium">Document</th>
                                    <th className="px-3 py-2 font-medium text-right">Views</th>
                                    <th className="px-3 py-2 font-medium text-right hidden sm:table-cell">Visitors</th>
                                    <th className="px-3 py-2 font-medium text-right">Avg. time</th>
                                    <th className="px-3 py-2 font-medium text-right hidden md:table-cell">Read-through</th>
                                    <th className="px-5 py-2 font-medium text-right hidden sm:table-cell">Downloads</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100 tabular-nums">
                                {top.map((row) => (
                                    <React.Fragment key={row.id}>
                                    <tr
                                        onClick={() => setSelected(selected === row.id ? null : row.id)}
                                        className={`cursor-pointer text-slate-700 ${selected === row.id ? 'bg-indigo-50/60' : 'hover:bg-slate-50'}`}
                                        aria-expanded={selected === row.id}
                                    >
                                        <td className="px-5 py-2.5">
                                            <div className="flex items-center gap-2.5 min-w-0">
                                                <span className="size-8 shrink-0 rounded-md overflow-hidden bg-slate-100 ring-1 ring-slate-200 flex items-center justify-center">
                                                    {row.thumbnail ? <img src={row.thumbnail} alt="" className="size-full object-cover object-top" /> : <FileText className="size-4 text-slate-400" />}
                                                </span>
                                                <span className="truncate font-medium text-slate-900 max-w-[240px]" title={row.title}>{row.title}</span>
                                            </div>
                                        </td>
                                        <td className="px-3 py-2.5 text-right font-semibold text-slate-900">{formatNumber(row.views)}</td>
                                        <td className="px-3 py-2.5 text-right hidden sm:table-cell">{formatNumber(row.visitors)}</td>
                                        <td className="px-3 py-2.5 text-right">{formatDuration(row.avgDuration)}</td>
                                        <td className="px-3 py-2.5 text-right hidden md:table-cell">
                                            <div className="inline-flex items-center gap-2">
                                                <span className="h-1.5 w-14 rounded-full bg-slate-100 overflow-hidden">
                                                    <span className="block h-full rounded-full bg-indigo-500" style={{ width: `${Math.round(row.completion * 100)}%` }} />
                                                </span>
                                                {Math.round(row.completion * 100)}%
                                            </div>
                                        </td>
                                        <td className="px-5 py-2.5 text-right hidden sm:table-cell">{formatNumber(row.downloads)}</td>
                                    </tr>
                                    </React.Fragment>
                                ))}
                            </tbody>
                        </table>
                        </div>
                    )}
                    {selected && top.some((r) => r.id === selected) && (
                        <div className="border-t border-slate-100 bg-indigo-50/30 px-5 pt-4 pb-5">
                            <p className="mb-3 text-sm font-semibold text-slate-900">
                                Page attention · <span className="font-normal text-slate-600">{top.find((r) => r.id === selected).title}</span>
                            </p>
                            <PageAttention pdfId={selected} days={days} />
                        </div>
                    )}
                </div>

                <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
                    <h3 className="text-sm font-semibold text-slate-900">Devices</h3>
                    <p className="text-xs text-slate-500">Share of views</p>
                    <div className="mt-4 space-y-4">
                        {[['desktop', 'Desktop', Monitor], ['mobile', 'Mobile & tablet', Smartphone]].map(([key, label, Icon]) => {
                            const value = Number(devices?.[key] || 0);
                            const pct = deviceTotal ? Math.round((value / deviceTotal) * 100) : 0;
                            return (
                                <div key={key}>
                                    <div className="flex items-center justify-between text-sm">
                                        <span className="inline-flex items-center gap-2 text-slate-700"><Icon className="size-4 text-slate-400" />{label}</span>
                                        <span className="font-semibold text-slate-900 tabular-nums">{pct}%</span>
                                    </div>
                                    <div className="mt-1.5 h-2 rounded-full bg-slate-100 overflow-hidden">
                                        <div className="h-full rounded-full bg-indigo-500" style={{ width: `${pct}%` }} />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                    <p className="mt-6 text-xs leading-relaxed text-slate-400">
                        Visitors are counted with a daily anonymised fingerprint. No IP addresses are stored.
                    </p>
                </div>
            </div>
        </div>
    );
};

const AnalyticsPage = () => {
    const { toast } = useToast();
    const pro = isPro();
    const [days, setDays] = useState(30);
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const preview = useMemo(() => sampleData(30), []);

    const load = (range) => {
        setLoading(true);
        setError(null);
        fetchAnalytics(range)
            .then((res) => setData(res.data))
            .catch((err) => setError(err.message))
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        if (pro) load(days);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [days, pro]);

    const handleExport = async () => {
        try {
            const res = await exportAnalytics(days);
            const rows = res.data.rows;
            if (!rows.length) {
                toast('No reading sessions in this period', { type: 'error' });
                return;
            }
            const cell = (v) => {
                let s = String(v ?? '');
                if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
                return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
            };
            const head = ['Started', 'PDF', 'PDF ID', 'Page', 'Device', 'Reading time (s)', 'Pages viewed', 'Furthest page', 'Total pages', 'Read-through %', 'Downloads', 'Prints'];
            const lines = rows.map((r) => [r.startedAt, r.pdf, r.pdfId, r.page, r.device, r.seconds, r.pagesViewed, r.furthestPage, r.totalPages,
                r.totalPages ? Math.min(100, Math.round((r.furthestPage / r.totalPages) * 100)) : '', r.downloads, r.prints]);
            const csv = '\uFEFF' + [head, ...lines].map((l) => l.map(cell).join(',')).join('\r\n');
            const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
            const a = document.createElement('a');
            a.href = url;
            a.download = `pdf-rack-reading-sessions-${days}d-${new Date().toISOString().slice(0, 10)}.csv`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            setTimeout(() => URL.revokeObjectURL(url), 1000);
        } catch (err) {
            toast(err.message || 'Could not export analytics', { type: 'error' });
        }
    };

    const handleReset = async () => {
        if (!window.confirm('Delete all collected analytics? This cannot be undone.')) return;
        try {
            await resetAnalytics();
            toast('Analytics data reset');
            load(days);
        } catch (err) {
            toast(err.message || 'Could not reset analytics', { type: 'error' });
        }
    };

    if (!pro) {
        return (
            <ProGate
                title="See how your PDFs are read"
                description="Privacy-friendly reading analytics for every PDF you embed."
                features={['Views, unique visitors and reading time', 'Page attention: time per page and where readers stop', 'CSV export and a weekly email report']}
            >
                <Dashboard data={preview} days={30} setDays={() => {}} />
            </ProGate>
        );
    }

    if (error) {
        return (
            <div className="rounded-2xl border border-red-200 bg-red-50 p-6 text-center">
                <p className="font-semibold text-red-700">Couldn't load analytics</p>
                <p className="mt-1 text-sm text-red-600">{error}</p>
            </div>
        );
    }

    if (!data) {
        return <div className="h-64 rounded-2xl border border-slate-200 bg-white animate-pulse" />;
    }

    return <Dashboard data={data} days={days} setDays={setDays} onReset={handleReset} onExport={handleExport} loading={loading} />;
};

export default AnalyticsPage;
