import { useState } from 'react';
import { Check, Copy } from 'lucide-react';
import type { Provenance, RunRef } from '@/lib/demo-kit/types';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { External, Label } from './chrome';
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 — and why
 * it WRAPS on a phone: a copyable command hidden off-screen defeats its purpose.
 */
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; sans?: boolean }[] = [
    { label: 'Environment package', value: provenance.envPackage },
    { label: 'Taskset', value: provenance.tasksetId },
    { label: 'verifiers version', value: provenance.verifiersVersion },
  ];
  if (run) {
    rows.push(
      { label: 'Run', value: run.id },
      { label: 'Model', value: run.model },
      { label: 'Captured', value: formatDate(run.capturedAt) },
      { label: 'Seed', value: String(run.seed) },
    );
    if (run.intervention) rows.push({ label: 'Intervention', value: run.intervention, sans: true });
  }

  return (
    <section
      aria-label="Provenance"
      className={cn('overflow-hidden rounded-xl border border-border bg-surface', className)}
    >
      <header className="border-b border-border px-4 py-2.5">
        <Label as="h3">Provenance</Label>
      </header>

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

      <div className="border-t border-border p-4">
        <div className="flex items-center justify-between gap-2">
          <Label as="h4">Run it yourself</Label>
          <Button variant="outline" size="touch" onClick={copy} className="lg:min-h-9">
            {copyState === 'copied' ? (
              <Check className="text-positive" aria-hidden="true" />
            ) : (
              <Copy aria-hidden="true" />
            )}
            {copyState === 'copied' ? 'Copied' : 'Copy'}
          </Button>
        </div>
        <pre className="mt-2 whitespace-pre-wrap break-all rounded-md border border-border bg-surface-3 p-3 font-mono text-code text-fg [font-feature-settings:'liga'_0] sm:whitespace-pre sm:break-normal sm:overflow-x-auto">
          <code>{provenance.command}</code>
        </pre>
        <p role="status" className="mt-1 text-small 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-4 py-3">
          <Label as="h4">Credits</Label>
          <ul className="mt-1.5 flex flex-col gap-1">
            {provenance.credits.map((credit) => (
              <li key={credit.href}>
                <a
                  href={credit.href}
                  className="inline-flex min-h-11 items-center font-mono text-mono-data text-accent-fg underline decoration-border-strong underline-offset-4 hover:decoration-accent-fg sm:min-h-0"
                  rel="noreferrer"
                >
                  {credit.label}
                  <External />
                </a>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </section>
  );
}
