import { Check, Copy, ExternalLink, Link2, UserRound } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { date } from '@/lib/format';
import { http } from '@/lib/http';

type ClientLink = { name: string | null; email: string; role: string; url: string; open: string; status: string; sent_at: string | null; last_viewed_at: string | null };

function CopyButton({ text, testId }: { text: string; testId?: string }) {
    const [copied, setCopied] = useState(false);
    const copy = async () => {
        try { await navigator.clipboard.writeText(text); setCopied(true); window.setTimeout(() => setCopied(false), 1500); } catch { /* clipboard blocked */ }
    };
    return <Button type="button" size="sm" variant="ghost" onClick={copy} data-testid={testId}>{copied ? <><Check className="h-4 w-4" /> Copied</> : <><Copy className="h-4 w-4" /> Copy</>}</Button>;
}

/**
 * Top of the quote editor: the staff preview link, and each client's personal link (the page they
 * see). "Open" goes through the staff click-through, so your visit isn't counted as the client's.
 */
export function ClientLinks({ quoteId, companyId, previewUrl, refreshKey }: { quoteId: number; companyId: number; previewUrl: string; refreshKey: number }) {
    const [data, setData] = useState<{ links: ClientLink[]; base: string } | null>(null);
    useEffect(() => {
        http<{ links: ClientLink[]; base: string }>('GET', `/quotes/${quoteId}/client-links`, undefined, { 'X-Company': String(companyId) }).then(setData).catch(() => {});
    }, [quoteId, companyId, refreshKey]);

    return (
        <div className="mb-4 divide-y divide-line rounded-md border border-line bg-surface text-sm" data-testid="quote-links">
            <div className="px-3 py-2.5" data-testid="client-links">
                <div className="mb-1.5 flex items-center gap-2 font-medium"><UserRound className="h-4 w-4 text-ink-muted" aria-hidden /> Client link</div>
                {data && data.links.length > 0 ? (
                    <ul className="space-y-1.5">
                        {data.links.map((l) => (
                            <li key={l.email} className="flex flex-wrap items-center gap-2" data-testid="client-link">
                                <span className="min-w-[9rem] truncate text-ink-muted" title={l.email}>{l.name || l.email}{l.role === 'cc' ? ' (cc)' : ''}</span>
                                <code className="min-w-0 flex-1 truncate rounded bg-stone-100 px-2 py-1 text-xs" data-testid="client-link-url">{l.url}</code>
                                <CopyButton text={l.url} />
                                <Button type="button" size="sm" variant="ghost" asChild><a href={l.open} target="_blank" rel="noreferrer"><ExternalLink className="h-4 w-4" /> Open</a></Button>
                                <span className="w-full text-xs text-ink-muted sm:w-auto">
                                    {l.status === 'scheduled' ? 'Scheduled' : 'Sent'}{l.sent_at ? ` ${date(l.sent_at)}` : ''}{l.last_viewed_at ? ` · last viewed ${date(l.last_viewed_at)}` : ' · not viewed yet'}
                                </span>
                            </li>
                        ))}
                    </ul>
                ) : (
                    <p className="text-ink-muted" data-testid="client-link-pending">
                        Not sent yet. When you send, each person gets their own personal link like <code className="rounded bg-stone-100 px-1 text-xs">{data?.base ?? '…/p/'}<span className="opacity-60">••••••••</span></code> and it appears here to copy or open.
                    </p>
                )}
                <p className="mt-1.5 text-xs text-ink-muted">Open uses a staff link, so your visit isn’t counted as the client viewing it (opening the copied link yourself may be).</p>
            </div>
            <div className="flex flex-wrap items-center gap-2 px-3 py-2">
                <span className="flex items-center gap-2 text-ink-muted"><Link2 className="h-4 w-4" aria-hidden /> Staff preview</span>
                <code className="min-w-0 flex-1 truncate rounded bg-stone-100 px-2 py-1 text-xs" data-testid="preview-url">{previewUrl}</code>
                <CopyButton text={previewUrl} />
                <span className="w-full text-xs text-ink-muted sm:w-auto">Only opens for people signed in to Spin Group Quotes.</span>
            </div>
        </div>
    );
}
