import { useState } from 'react';
import {
  CheckCircle2, XCircle, AlertCircle, Loader2, Clock,
  ChevronDown, ChevronRight, Plus, Pencil, Trash2, History,
} from 'lucide-react';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '../ui/empty';
import { trpc } from '@/lib/trpc';
import { useFormatPrefs, formatTs, formatDuration } from '@/lib/date';

// ---------------------------------------------------------------------------
// Types inferred from router return
// ---------------------------------------------------------------------------

type RunSummary = {
  id: string;
  agentId: string;
  status: 'running' | 'completed' | 'failed' | 'partial';
  startedAt: number;
  completedAt: number | null | undefined;
  actionCounts: { created: number; updated: number; deleted: number };
};

type RunAction = {
  id: string;
  runId: string;
  verb: string;
  entityType: string;
  entityId: string | null | undefined;
  entityTitle: string | null | undefined;
  createdAt: number;
};

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

function statusBadge(status: string) {
  switch (status) {
    case 'completed':
      return (
        <Badge variant="secondary" className="gap-1 shrink-0 text-[10px] py-0">
          <CheckCircle2 className="size-2.5" /> Done
        </Badge>
      );
    case 'failed':
      return (
        <Badge variant="destructive" className="gap-1 shrink-0 text-[10px] py-0">
          <XCircle className="size-2.5" /> Failed
        </Badge>
      );
    case 'running':
      return (
        <Badge variant="outline" className="gap-1 shrink-0 text-[10px] py-0">
          <Loader2 className="size-2.5 animate-spin" /> Running
        </Badge>
      );
    case 'partial':
      return (
        <Badge variant="outline" className="gap-1 text-amber-600 shrink-0 text-[10px] py-0">
          <AlertCircle className="size-2.5" /> Partial
        </Badge>
      );
    default:
      return <Badge variant="outline" className="shrink-0 text-[10px] py-0">{status}</Badge>;
  }
}

function actionSummary(counts: RunSummary['actionCounts']): string {
  const parts: string[] = [];
  if (counts.created > 0) parts.push(`${counts.created} created`);
  if (counts.updated > 0) parts.push(`${counts.updated} updated`);
  if (counts.deleted > 0) parts.push(`${counts.deleted} deleted`);
  return parts.join(' · ') || 'No changes';
}

const VERB_ICON: Record<string, React.ReactNode> = {
  created: <Plus className="size-3 text-emerald-500 shrink-0" />,
  updated: <Pencil className="size-3 text-blue-500 shrink-0" />,
  deleted: <Trash2 className="size-3 text-destructive shrink-0" />,
};

// ---------------------------------------------------------------------------
// Expanded run actions
// ---------------------------------------------------------------------------

function RunActionList({ runId }: { runId: string }) {
  const query = trpc.agent.runActions.useQuery({ runId });

  if (query.isPending) {
    return (
      <div className="px-3 pb-3 flex flex-col gap-1.5">
        {[0, 1, 2].map(i => <Skeleton key={i} className="h-5 w-full rounded" />)}
      </div>
    );
  }

  const actions = (query.data ?? []) as RunAction[];
  if (actions.length === 0) {
    return <p className="px-3 pb-3 text-xs text-muted-foreground">No actions recorded.</p>;
  }

  return (
    <div className="px-3 pb-3 flex flex-col gap-1">
      {actions.map(a => (
        <div key={a.id} className="flex items-center gap-2 text-xs">
          {VERB_ICON[a.verb] ?? <span className="size-3 shrink-0" />}
          <span className="text-muted-foreground capitalize">{a.verb}</span>
          <span className="text-foreground/70 capitalize">{a.entityType}</span>
          {a.entityTitle && (
            <span className="text-foreground truncate max-w-[200px]">{a.entityTitle}</span>
          )}
        </div>
      ))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Single run row
// ---------------------------------------------------------------------------

function RunRow({ run }: { run: RunSummary }) {
  const [expanded, setExpanded] = useState(false);
  const prefs = useFormatPrefs();
  const duration = formatDuration(run.startedAt, run.completedAt);
  const hasActions = run.actionCounts.created + run.actionCounts.updated + run.actionCounts.deleted > 0;

  return (
    <div className="rounded-lg border bg-muted/20 overflow-hidden">
      <button
        className="w-full text-left px-3 py-2.5 flex items-start gap-2"
        onClick={() => hasActions && setExpanded(v => !v)}
        disabled={!hasActions}
      >
        <div className="flex-1 min-w-0 flex flex-col gap-1">
          <div className="flex items-center gap-2 flex-wrap">
            {statusBadge(run.status)}
            <span className="text-xs text-muted-foreground">{formatTs(run.startedAt, prefs)}</span>
            {duration && (
              <span className="flex items-center gap-1 text-xs text-muted-foreground">
                <Clock className="size-3" />{duration}
              </span>
            )}
          </div>
          <p className="text-xs text-muted-foreground">{actionSummary(run.actionCounts)}</p>
        </div>
        {hasActions && (
          <span className="mt-0.5 shrink-0">
            {expanded
              ? <ChevronDown className="size-3.5 text-muted-foreground" />
              : <ChevronRight className="size-3.5 text-muted-foreground" />}
          </span>
        )}
      </button>

      {expanded && <RunActionList runId={run.id} />}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Sheet
// ---------------------------------------------------------------------------

export function AgentRunHistorySheet({
  agentId,
  agentName,
  open,
  onOpenChange,
}: {
  agentId: string;
  agentName: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const runsQuery = trpc.agent.runs.useQuery(
    { agentId, limit: 30 },
    { enabled: open },
  );

  const runs = (runsQuery.data ?? []) as RunSummary[];

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full sm:max-w-md flex flex-col gap-0 p-0">
        <SheetHeader className="px-5 pt-5 pb-4">
          <SheetTitle className="text-base font-semibold">{agentName}</SheetTitle>
          <p className="text-xs text-muted-foreground -mt-1">Run history</p>
        </SheetHeader>

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

            {!runsQuery.isPending && runs.length === 0 && (
              <Empty className="border-none py-12">
                <EmptyHeader>
                  <EmptyMedia variant="icon">
                    <History />
                  </EmptyMedia>
                  <EmptyTitle className="text-sm">No runs yet</EmptyTitle>
                  <EmptyDescription className="text-xs">
                    Runs will appear here after the agent executes.
                  </EmptyDescription>
                </EmptyHeader>
              </Empty>
            )}

            {!runsQuery.isPending && runs.map(run => (
              <RunRow key={run.id} run={run} />
            ))}
          </div>
        </ScrollArea>
      </SheetContent>
    </Sheet>
  );
}
