// components/LeadsPage.jsx
import React, { useCallback, useEffect, useState } from 'react';
import { Download, Mail, Search, Trash2, Users } from 'lucide-react';
import { fetchLeads, deleteLeads } from '../api/pdfs';
import { isPro } from '../utils/shortcode';
import { useToast } from './Toast';
import ProGate from './ProGate';
import Pagination from './Pagination';

const PER_PAGE = 25;

const SAMPLE = [
    { id: 1, name: 'Jane Reader', email: 'jane@example.com', pdfTitle: 'Product catalogue 2026', consent: true, createdAt: '2026-10-20T09:12:00Z' },
    { id: 2, name: '', email: 'sam@example.org', pdfTitle: 'Annual report', consent: true, createdAt: '2026-10-19T16:40:00Z' },
    { id: 3, name: 'Alex Kim', email: 'alex@example.net', pdfTitle: 'Product catalogue 2026', consent: false, createdAt: '2026-10-18T11:05:00Z' },
];

const formatDate = (value) => {
    const d = new Date(value);
    return Number.isNaN(d.getTime()) ? value : d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
};

const csvCell = (value) => {
    let s = String(value ?? '');
    if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`; // keep spreadsheets from running formulas
    return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};

const downloadCsv = (items) => {
    const rows = [['Name', 'Email', 'PDF', 'Consent', 'Page', 'Date']]
        .concat(items.map((l) => [l.name, l.email, l.pdfTitle, l.consent ? 'yes' : 'no', l.pageUrl, l.createdAt]));
    const csv = '﻿' + rows.map((r) => r.map(csvCell).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-leads-${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
};

const LeadsTable = ({ items, selected, onToggle, onToggleAll }) => {
    const allSelected = items.length > 0 && items.every((l) => selected.has(l.id));
    return (
        <div className="overflow-x-auto">
            <table className="w-full text-sm">
                <thead>
                    <tr className="bg-slate-50 border-b border-slate-200 text-left text-xs font-semibold uppercase tracking-wider text-slate-500">
                        <th className="w-[44px] pl-4 pr-2 py-3">
                            <input
                                type="checkbox"
                                checked={allSelected}
                                onChange={onToggleAll}
                                aria-label="Select all on this page"
                                className="size-4 appearance-auto accent-indigo-600 cursor-pointer"
                                style={{ padding: 0 }}
                            />
                        </th>
                        <th className="px-3 py-3">Contact</th>
                        <th className="px-3 py-3">PDF</th>
                        <th className="px-3 py-3 w-[90px]">Consent</th>
                        <th className="px-3 py-3 pr-4 w-[190px]">Date</th>
                    </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                    {items.map((l) => (
                        <tr key={l.id} className={selected.has(l.id) ? 'bg-indigo-50/50' : 'hover:bg-slate-50'}>
                            <td className="pl-4 pr-2 py-3">
                                <input
                                    type="checkbox"
                                    checked={selected.has(l.id)}
                                    onChange={() => onToggle(l.id)}
                                    aria-label={`Select ${l.email}`}
                                    className="size-4 appearance-auto accent-indigo-600 cursor-pointer"
                                    style={{ padding: 0 }}
                                />
                            </td>
                            <td className="px-3 py-3 min-w-0">
                                <span className="block font-medium text-slate-900 truncate">{l.name || <span className="text-slate-400 font-normal">No name</span>}</span>
                                <a href={`mailto:${l.email}`} className="block text-xs text-indigo-600 hover:text-indigo-800 truncate">{l.email}</a>
                            </td>
                            <td className="px-3 py-3 text-slate-700">
                                <span className="block truncate max-w-[280px]" title={l.pdfTitle}>{l.pdfTitle}</span>
                                {l.pageUrl && (
                                    <a href={l.pageUrl} target="_blank" rel="noreferrer" className="block text-xs text-slate-400 hover:text-slate-600 truncate max-w-[280px]">
                                        {l.pageUrl.replace(/^https?:\/\//, '')}
                                    </a>
                                )}
                            </td>
                            <td className="px-3 py-3">
                                {l.consent
                                    ? <span className="rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700">Yes</span>
                                    : <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-500">No</span>}
                            </td>
                            <td className="px-3 py-3 pr-4 text-slate-500 tabular-nums whitespace-nowrap">{formatDate(l.createdAt)}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

const LeadsPage = () => {
    const { toast } = useToast();
    const pro = isPro();
    const [data, setData] = useState(null);
    const [page, setPage] = useState(1);
    const [search, setSearch] = useState('');
    const [query, setQuery] = useState('');
    const [pdf, setPdf] = useState(0);
    const [selected, setSelected] = useState(new Set());
    const [exporting, setExporting] = useState(false);

    // Debounce typing into the search box.
    useEffect(() => {
        const t = setTimeout(() => setQuery(search.trim()), 300);
        return () => clearTimeout(t);
    }, [search]);
    useEffect(() => setPage(1), [query, pdf]);

    const load = useCallback(() => {
        if (!pro) return;
        fetchLeads({ page, perPage: PER_PAGE, search: query, pdf })
            .then((res) => setData(res.data))
            .catch((err) => toast(err.message || 'Could not load leads', { type: 'error' }));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pro, page, query, pdf]);

    useEffect(load, [load]);

    const items = data?.items || [];
    const totalPages = Math.max(1, Math.ceil((data?.total || 0) / PER_PAGE));

    const toggle = (id) => setSelected((cur) => {
        const next = new Set(cur);
        if (next.has(id)) next.delete(id);
        else next.add(id);
        return next;
    });
    const toggleAll = () => setSelected((cur) => {
        const next = new Set(cur);
        const all = items.every((l) => next.has(l.id));
        items.forEach((l) => (all ? next.delete(l.id) : next.add(l.id)));
        return next;
    });

    const handleExport = async () => {
        setExporting(true);
        try {
            const res = await fetchLeads({ page: 1, perPage: 50000, search: query, pdf });
            downloadCsv(res.data.items);
        } catch (err) {
            toast(err.message || 'Could not export leads', { type: 'error' });
        } finally {
            setExporting(false);
        }
    };

    const handleDelete = async () => {
        const count = selected.size;
        if (!window.confirm(`Delete ${count} lead${count === 1 ? '' : 's'} permanently?`)) return;
        try {
            await deleteLeads(Array.from(selected));
            setSelected(new Set());
            toast(`${count} lead${count === 1 ? '' : 's'} deleted`);
            load();
        } catch (err) {
            toast(err.message || 'Could not delete leads', { type: 'error' });
        }
    };

    const toolbar = (
        <div className="flex flex-wrap items-center gap-3">
            <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-slate-400" />
                <input
                    type="search"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder="Search name or email"
                    className="block w-full pl-9 pr-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>
            <select
                value={pdf}
                onChange={(e) => setPdf(Number(e.target.value))}
                className="w-56 px-3 py-2 bg-white border border-slate-200 rounded-lg text-sm"
                aria-label="Filter by PDF"
            >
                <option value={0}>All PDFs</option>
                {(data?.pdfs || []).map((p) => (
                    <option key={p.id} value={p.id}>{p.title} ({p.count})</option>
                ))}
            </select>
            {selected.size > 0 && (
                <button
                    type="button"
                    onClick={handleDelete}
                    className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-red-500 text-sm font-semibold text-white hover:bg-red-600 hover:text-white"
                >
                    <Trash2 className="size-4" /> Delete {selected.size}
                </button>
            )}
            <button
                type="button"
                onClick={handleExport}
                disabled={exporting || !data?.total}
                className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border border-slate-200 bg-white text-sm font-semibold text-slate-700 hover:border-indigo-300 hover:text-indigo-700 disabled:opacity-50"
            >
                {exporting ? <span className="size-4 border-2 border-slate-300 border-t-indigo-600 rounded-full animate-spin" /> : <Download className="size-4" />}
                Export CSV
            </button>
        </div>
    );

    if (!pro) {
        return (
            <ProGate
                title="Turn readers into leads"
                description="Ask for an email before a PDF opens or after a free preview, then export your list."
                features={['Sign-up form before reading or after N pages', 'Optional name and consent checkbox', 'Search, filter and export leads as CSV']}
            >
                <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                    <LeadsTable items={SAMPLE} selected={new Set()} onToggle={() => {}} onToggleAll={() => {}} />
                </div>
            </ProGate>
        );
    }

    return (
        <div className="space-y-4">
            {toolbar}
            <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                {!data ? (
                    <div className="p-10 flex justify-center">
                        <span className="size-6 border-2 border-slate-200 border-t-indigo-600 rounded-full animate-spin" />
                    </div>
                ) : items.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-16 text-center px-4">
                        <span className="rounded-2xl bg-indigo-50 p-4 mb-4 text-indigo-600">
                            {query || pdf ? <Search className="size-7" /> : <Users className="size-7" />}
                        </span>
                        <h3 className="text-base font-semibold text-slate-900">{query || pdf ? 'No matching leads' : 'No leads yet'}</h3>
                        <p className="mt-1 text-sm text-slate-500 max-w-sm">
                            {query || pdf
                                ? 'Try another search or PDF.'
                                : <>Open a PDF's details in the Library and turn on <strong className="font-semibold text-slate-700"><Mail className="inline size-3.5 -mt-0.5" /> Lead capture</strong>.</>}
                        </p>
                    </div>
                ) : (
                    <LeadsTable items={items} selected={selected} onToggle={toggle} onToggleAll={toggleAll} />
                )}
            </div>
            {data && data.total > 0 && (
                <div className="flex flex-wrap items-center justify-between gap-3">
                    <p className="text-sm text-slate-500">{data.total} lead{data.total === 1 ? '' : 's'}</p>
                    {totalPages > 1 && <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />}
                </div>
            )}
        </div>
    );
};

export default LeadsPage;
