import { useState } from 'react';
import { Check, Copy, ExternalLink } from 'lucide-react';
import type { Provenance, RunRef } from '@/lib/demo-kit/types';
import { Button } from '@/components/ui/button';
import * as st from '@/content/styles';
import { cn } from '@/lib/utils';
import { formatDate } from './format';

export interface ProvenanceCardProps {
  provenance: Provenance;
  /** The run currently on screen, if the page is showing one. */
  run?: RunRef;
  className?: string;
}

type CopyState = 'idle' | 'copied' | 'failed';

/**
 * Where these numbers came from, and the command that reproduces them.
 *
 * The command is the load-bearing element. Everything else on this page is us
 * telling you what happened; this is the line you paste into your own terminal
 * to find out for yourself, which is why it is verbatim and copy-pasteable
 * rather than prettified into something that would not actually run.
 */
export function ProvenanceCard({ provenance, run, className }: ProvenanceCardProps) {
  const [copyState, setCopyState] = useState<CopyState>('idle');

  const copy = async () => {
    try {
      // `navigator.clipboard` is undefined on a non-secure origin, which is
      // exactly what a colleague testing over a LAN IP will hit. Fail visibly.
      await navigator.clipboard.writeText(provenance.command);
      setCopyState('copied');
      window.setTimeout(() => setCopyState('idle'), 2000);
    } catch {
      setCopyState('failed');
    }
  };

  const rows: { label: string; value: string; mono?: boolean }[] = [
    { label: 'Environment package', value: provenance.envPackage, mono: true },
    { label: 'Taskset', value: provenance.tasksetId, mono: true },
    { label: 'verifiers version', value: provenance.verifiersVersion, mono: true },
  ];
  if (run) {
    rows.push(
      { label: 'Model', value: run.model, mono: true },
      { label: 'Captured', value: formatDate(run.capturedAt) },
      { label: 'Seed', value: String(run.seed), mono: true },
    );
    if (run.intervention) rows.push({ label: 'Intervention', value: run.intervention });
  }

  return (
    <section aria-label="Provenance" className={cn('card overflow-hidden', className)}>
      <header className="border-b border-border px-3 py-2">
        <h3 className="text-sm font-semibold">Provenance</h3>
      </header>

      <dl className="divide-y divide-border">
        {rows.map((row) => (
          <div key={row.label} className="flex items-baseline gap-3 px-3 py-2">
            <dt className="flex-1 text-sm text-muted">{row.label}</dt>
            <dd
              className={cn(
                'min-w-0 break-all text-right text-sm',
                row.mono && 'nums font-mono text-xs',
              )}
            >
              {row.value}
            </dd>
          </div>
        ))}
      </dl>

      <div className="border-t border-border p-3">
        <div className="flex items-center justify-between gap-2">
          <h4 className="text-xs font-semibold uppercase tracking-wide text-muted">
            Run it yourself
          </h4>
          <Button variant="outline" size="sm" className="tap" onClick={copy}>
            {copyState === 'copied' ? (
              <Check className="text-positive" aria-hidden="true" />
            ) : (
              <Copy aria-hidden="true" />
            )}
            {copyState === 'copied' ? 'Copied' : 'Copy'}
          </Button>
        </div>
        <pre className={cn(st.codeBlock, 'mt-2')}>
          <code>{provenance.command}</code>
        </pre>
        <p role="status" className="mt-1 text-xs text-muted">
          {copyState === 'copied'
            ? 'Command copied to your clipboard.'
            : copyState === 'failed'
              ? 'Your browser blocked clipboard access — select the command above and copy it manually.'
              : ''}
        </p>
      </div>

      {provenance.credits.length > 0 ? (
        <div className="border-t border-border px-3 py-2.5">
          <h4 className="text-xs font-semibold uppercase tracking-wide text-muted">
            Built on
          </h4>
          <ul className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1">
            {provenance.credits.map((credit) => (
              <li key={credit.href}>
                <a
                  href={credit.href}
                  className={cn(st.link, 'inline-flex items-center gap-1 text-sm')}
                  rel="noreferrer"
                >
                  {credit.label}
                  <ExternalLink className="size-3" aria-hidden="true" />
                </a>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </section>
  );
}
