import { useState } from 'react';
import {
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
  ChevronDown,
  ChevronRight,
  Clock,
  FileCheck,
  FilePlus,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { trpc } from '@/lib/trpc';
import { useFormatPrefs, formatTs, formatDuration } from '@/lib/date';
import type { AgentRunLog } from '../../../shared/api-types';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function statusBadge(status: string) {
  switch (status) {
    case 'success':
      return (
        <Badge variant="secondary" className="gap-1 text-emerald-600 dark:text-emerald-400 shrink-0">
          <CheckCircle2 className="size-3" /> Success
        </Badge>
      );
    case 'error':
      return (
        <Badge variant="destructive" className="gap-1 shrink-0">
          <XCircle className="size-3" /> Error
        </Badge>
      );
    case 'running':
      return (
        <Badge variant="outline" className="gap-1 shrink-0">
          <Loader2 className="size-3 animate-spin" /> Running
        </Badge>
      );
    case 'partial':
      return (
        <Badge variant="outline" className="gap-1 text-amber-600 shrink-0">
          <AlertCircle className="size-3" /> Partial
        </Badge>
      );
    default:
      return <Badge variant="outline" className="shrink-0">{status}</Badge>;
  }
}

// ---------------------------------------------------------------------------
// Per-run row
// ---------------------------------------------------------------------------

function RunRow({ run }: { run: AgentRunLog }) {
  const prefs = useFormatPrefs();
  const [errorsOpen, setErrorsOpen] = useState(false);
  const hasErrors = (run.errors ?? []).length > 0;
  const duration = formatDuration(run.startedAt, run.completedAt);

  return (
    <div className="rounded-lg border bg-muted/20 overflow-hidden">
      <div className="flex items-center gap-3 px-3 py-2 text-xs">
        {statusBadge(run.status)}

        <span className="text-muted-foreground shrink-0">{formatTs(run.startedAt, prefs)}</span>

        {duration && (
          <span className="flex items-center gap-1 text-muted-foreground shrink-0">
            <Clock className="size-3" />
            {duration}
          </span>
        )}

        <span className="flex items-center gap-1 text-muted-foreground shrink-0">
          <FileCheck className="size-3" />
          {run.itemsProcessed} processed
        </span>

        <span className="flex items-center gap-1 text-muted-foreground shrink-0">
          <FilePlus className="size-3" />
          {run.itemsCreated} created
        </span>

        {hasErrors && (
          <button
            onClick={() => setErrorsOpen(v => !v)}
            className="ml-auto flex items-center gap-1 text-destructive hover:text-destructive/80 transition-colors"
          >
            {errorsOpen ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}
            {run.errors.length} {run.errors.length === 1 ? 'error' : 'errors'}
          </button>
        )}
      </div>

      {hasErrors && errorsOpen && (
        <div className="border-t px-3 py-2 flex flex-col gap-1">
          {run.errors.map((err, i) => (
            <p key={i} className="text-xs text-destructive font-mono break-all">{err}</p>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// AgentRunLog
// ---------------------------------------------------------------------------

export function AgentRunLog({ agentId, expanded }: { agentId: string; expanded: boolean }) {
  const runsQuery = trpc.agent.runs.useQuery(
    { agentId, limit: 10 },
    { enabled: expanded },
  );

  if (!expanded) return null;

  return (
    <div>
      <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">
        Run History
      </p>

      {runsQuery.isPending && (
        <div className="flex flex-col gap-2">
          {[0, 1, 2].map(i => (
            <Skeleton key={i} className="h-9 w-full rounded-lg" />
          ))}
        </div>
      )}

      {!runsQuery.isPending && (runsQuery.data ?? []).length === 0 && (
        <p className="text-xs text-muted-foreground">No runs yet.</p>
      )}

      {!runsQuery.isPending && (runsQuery.data ?? []).length > 0 && (
        <div className="flex flex-col gap-2">
          {(runsQuery.data as AgentRunLog[]).map(run => (
            <RunRow key={run.id} run={run} />
          ))}
        </div>
      )}
    </div>
  );
}
