// components/ShareLinks.jsx
import React, { useEffect, useState } from 'react';
import { Link2, Plus, Copy, Ban, Crown, Eye, Clock } from 'lucide-react';
import { fetchLinks, createLink, revokeLink } from '../api/pdfs';
import { isPro } from '../utils/shortcode';
import { useToast } from './Toast';

const EXPIRY = [
    ['', 'Never'],
    ['1', '1 day'],
    ['7', '7 days'],
    ['30', '30 days'],
    ['custom', 'Pick a date'],
];

const STATUS = {
    active: ['Active', 'bg-emerald-50 text-emerald-700'],
    expired: ['Expired', 'bg-slate-100 text-slate-500'],
    used_up: ['View limit reached', 'bg-amber-50 text-amber-700'],
    revoked: ['Turned off', 'bg-slate-100 text-slate-500'],
};

const formatDate = (iso) => (iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '');

const NewLinkForm = ({ pdfId, onCreated, onCancel }) => {
    const { toast } = useToast();
    const [label, setLabel] = useState('');
    const [expiry, setExpiry] = useState('7');
    const [date, setDate] = useState('');
    const [maxViews, setMaxViews] = useState('');
    const [mode, setMode] = useState('reader');
    const [allowDownload, setAllowDownload] = useState(true);
    const [saving, setSaving] = useState(false);

    const submit = async (e) => {
        e.preventDefault();
        let expiresAt = null;
        if (expiry === 'custom') {
            if (!date) return toast('Pick an expiry date', { type: 'error' });
            expiresAt = new Date(date).toISOString();
        } else if (expiry) {
            expiresAt = new Date(Date.now() + Number(expiry) * 86400000).toISOString();
        }
        setSaving(true);
        try {
            const res = await createLink({ pdfId, label, expiresAt, maxViews: maxViews === '' ? null : Number(maxViews), mode, allowDownload });
            onCreated(res.data.link);
        } catch (err) {
            toast(err.message || 'Could not create the link', { type: 'error' });
        } finally {
            setSaving(false);
        }
    };

    const input = 'block w-full px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-sm text-slate-900';

    return (
        <form onSubmit={submit} className="mt-3 space-y-3 rounded-lg bg-slate-50 p-3">
            <label className="block">
                <span className="block text-xs font-medium text-slate-600 mb-1">Label (only you see it)</span>
                <input type="text" value={label} onChange={(e) => setLabel(e.target.value)} placeholder="e.g. Acme Corp proposal" className={input} />
            </label>
            <div className="grid grid-cols-2 gap-3">
                <label className="block">
                    <span className="block text-xs font-medium text-slate-600 mb-1">Expires</span>
                    <select value={expiry} onChange={(e) => setExpiry(e.target.value)} className={input}>
                        {EXPIRY.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                    </select>
                </label>
                <label className="block">
                    <span className="block text-xs font-medium text-slate-600 mb-1">Max. viewers</span>
                    <input type="number" min="1" value={maxViews} onChange={(e) => setMaxViews(e.target.value)} placeholder="Unlimited" className={input} />
                </label>
            </div>
            {expiry === 'custom' && (
                <input type="datetime-local" value={date} onChange={(e) => setDate(e.target.value)} className={input} />
            )}
            <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">
                    {[['reader', 'Reader'], ['slider', 'Slider'], ['flipbook', 'Flipbook']].map(([v, l]) => (
                        <button
                            key={v}
                            type="button"
                            onClick={() => setMode(v)}
                            className={`px-2.5 py-1 rounded-md text-xs font-medium ${mode === v ? 'bg-indigo-600 text-white' : 'text-slate-500 hover:text-slate-800'}`}
                        >
                            {l}
                        </button>
                    ))}
                </div>
                <label className="inline-flex items-center gap-2 text-xs text-slate-600">
                    <input type="checkbox" checked={allowDownload} onChange={(e) => setAllowDownload(e.target.checked)} className="size-4 appearance-auto accent-indigo-600 cursor-pointer" style={{ padding: 0 }} />
                    Allow download &amp; print
                </label>
            </div>
            <p className="text-[11px] leading-4 text-slate-500">
                A viewer is counted once per browser per 12 hours. The link skips this PDF's password and sign-up form.
            </p>
            <div className="flex justify-end gap-2">
                <button type="button" onClick={onCancel} className="px-3 py-1.5 text-sm font-medium text-slate-600 hover:text-slate-900">Cancel</button>
                <button type="submit" disabled={saving} className="px-3 py-1.5 rounded-lg bg-indigo-600 text-sm font-semibold text-white hover:bg-indigo-700 disabled:opacity-60">
                    {saving ? 'Creating…' : 'Create link'}
                </button>
            </div>
        </form>
    );
};

/**
 * Expiring & limited share links for one PDF (Pro).
 */
const ShareLinks = ({ pdfId }) => {
    const { toast, copy } = useToast();
    const pro = isPro();
    const [links, setLinks] = useState(null);
    const [creating, setCreating] = useState(false);

    useEffect(() => {
        if (!pro || !pdfId) return;
        fetchLinks(pdfId)
            .then((res) => setLinks(res.data.links))
            .catch(() => setLinks([]));
    }, [pro, pdfId]);

    const handleCreated = (link) => {
        setLinks((list) => [link, ...(list || [])]);
        setCreating(false);
        copy(link.url, 'Link created and copied');
    };

    const handleRevoke = async (link) => {
        if (!window.confirm('Turn this link off? Anyone using it will no longer be able to open the PDF.')) return;
        try {
            const res = await revokeLink(link.id);
            setLinks((list) => list.map((l) => (l.id === link.id ? res.data.link : l)));
            toast('Link turned off');
        } catch (err) {
            toast(err.message || 'Could not turn the link off', { type: 'error' });
        }
    };

    return (
        <div className="rounded-xl border border-slate-200 p-4">
            <div className="flex items-start gap-3">
                <span className={`mt-0.5 rounded-lg p-1.5 ${links?.some((l) => l.status === 'active') ? 'bg-indigo-50 text-indigo-600' : 'bg-slate-100 text-slate-400'}`}>
                    <Link2 className="size-4" />
                </span>
                <div className="min-w-0 flex-1">
                    <div className="flex items-center justify-between gap-2">
                        <p className="flex items-center gap-1.5 text-sm font-medium text-slate-800">
                            Share links
                            {!pro && (
                                <span className="inline-flex items-center gap-0.5 rounded-full bg-amber-100 px-1.5 py-px text-[10px] font-bold uppercase text-amber-700">
                                    <Crown className="size-3" />Pro
                                </span>
                            )}
                        </p>
                        {pro && !creating && (
                            <button type="button" onClick={() => setCreating(true)} className="inline-flex items-center gap-1 text-xs font-semibold text-indigo-600 hover:text-indigo-800">
                                <Plus className="size-3.5" /> New link
                            </button>
                        )}
                    </div>
                    <p className="text-xs text-slate-500 mt-0.5">Private links that open this PDF on its own page, with an expiry date or a viewer limit. The file address stays hidden.</p>

                    {!pro && window.pdfRack?.upgradeUrl && (
                        <a href={window.pdfRack.upgradeUrl} className="mt-2 inline-block text-xs font-semibold text-amber-700 hover:text-amber-900">Upgrade to Pro →</a>
                    )}

                    {pro && creating && <NewLinkForm pdfId={pdfId} onCreated={handleCreated} onCancel={() => setCreating(false)} />}

                    {pro && links && links.length > 0 && (
                        <ul className="mt-3 divide-y divide-slate-100 rounded-lg border border-slate-200">
                            {links.map((link) => {
                                const [statusLabel, statusClass] = STATUS[link.status] || STATUS.active;
                                const active = link.status === 'active';
                                return (
                                    <li key={link.id} className="flex items-center gap-3 px-3 py-2.5">
                                        <div className="min-w-0 flex-1">
                                            <p className="flex items-center gap-2 text-sm">
                                                <span className={`truncate font-medium ${active ? 'text-slate-800' : 'text-slate-400'}`}>{link.label || 'Untitled link'}</span>
                                                <span className={`shrink-0 rounded-full px-1.5 py-px text-[10px] font-semibold ${statusClass}`}>{statusLabel}</span>
                                            </p>
                                            <p className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-slate-500">
                                                <span className="inline-flex items-center gap-1"><Eye className="size-3" />{link.views}{link.maxViews ? ` / ${link.maxViews}` : ''} viewer{link.views === 1 && !link.maxViews ? '' : 's'}</span>
                                                <span className="inline-flex items-center gap-1"><Clock className="size-3" />{link.expiresAt ? `${link.status === 'expired' ? 'Expired' : 'Expires'} ${formatDate(link.expiresAt)}` : 'No expiry'}</span>
                                                <span className="capitalize">{link.mode}</span>
                                                {!link.allowDownload && <span>No download</span>}
                                            </p>
                                        </div>
                                        {active && (
                                            <>
                                                <button type="button" onClick={() => copy(link.url, 'Link copied')} title="Copy link" className="p-1.5 rounded-md text-slate-500 hover:bg-indigo-50 hover:text-indigo-600">
                                                    <Copy className="size-4" />
                                                </button>
                                                <button type="button" onClick={() => handleRevoke(link)} title="Turn off" className="p-1.5 rounded-md text-slate-500 hover:bg-red-50 hover:text-red-600">
                                                    <Ban className="size-4" />
                                                </button>
                                            </>
                                        )}
                                    </li>
                                );
                            })}
                        </ul>
                    )}
                </div>
            </div>
        </div>
    );
};

export default ShareLinks;
