import { useState, useEffect } from "react";
import { Link } from "@tanstack/react-router";
import { trpc } from "@/lib/trpc";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/Skeleton";
import { Button } from "@/components/ui/button";
import { StatusDot } from "@/components/StatusDot";
import { formatRelativeTime } from "@/lib/utils";
import { modeLabel } from "@/lib/labels";

export function AgentDetailsPanel({ agentId }: { agentId: string }) {
  return (
    <div className="h-full overflow-y-auto p-4 space-y-6">
      <section>
        <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Metadata</h3>
        <MetadataSection agentId={agentId} />
      </section>
      <section>
        <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Input Files</h3>
        <InputFilesSection agentId={agentId} />
      </section>
      <section>
        <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Effective Prompt</h3>
        <EffectivePromptSection agentId={agentId} />
      </section>
    </div>
  );
}

function MetadataSection({ agentId }: { agentId: string }) {
  const query = trpc.getAgent.useQuery({ id: agentId });

  if (query.isLoading) {
    return (
      <div className="space-y-2">
        {Array.from({ length: 5 }).map((_, i) => (
          <Skeleton key={i} variant="line" />
        ))}
      </div>
    );
  }

  if (query.isError) {
    return (
      <div className="space-y-2">
        <p className="text-sm text-destructive">{query.error.message}</p>
        <Button variant="outline" size="sm" onClick={() => void query.refetch()}>Retry</Button>
      </div>
    );
  }

  const agent = query.data;
  if (!agent) return null;

  const showExitCode = !['idle', 'running', 'waiting_for_input'].includes(agent.status);

  const rows: Array<{ label: string; value: React.ReactNode }> = [
    {
      label: 'Status',
      value: (
        <span className="flex items-center gap-1.5">
          <StatusDot status={agent.status} size="sm" />
          {agent.status}
        </span>
      ),
    },
    {
      label: 'Mode',
      value: modeLabel(agent.mode),
    },
    {
      label: 'Provider',
      value: agent.provider,
    },
    {
      label: 'Initiative',
      value: agent.initiativeId ? (
        <Link
          to="/initiatives/$initiativeId"
          params={{ initiativeId: agent.initiativeId }}
          className="underline underline-offset-2"
        >
          {(agent as { initiativeName?: string | null }).initiativeName ?? agent.initiativeId}
        </Link>
      ) : '—',
    },
    {
      label: 'Task',
      value: (agent as { taskName?: string | null }).taskName ?? (agent.taskId ? agent.taskId : '—'),
    },
    {
      label: 'Created',
      value: formatRelativeTime(String(agent.createdAt)),
    },
  ];

  if (showExitCode) {
    rows.push({
      label: 'Exit Code',
      value: (
        <span className={agent.exitCode === 1 ? 'text-destructive' : ''}>
          {agent.exitCode ?? '—'}
        </span>
      ),
    });
  }

  return (
    <div>
      {rows.map(({ label, value }) => (
        <div key={label} className="flex items-center gap-4 py-1.5 border-b border-border/30 last:border-0">
          <span className="w-28 shrink-0 text-xs text-muted-foreground">{label}</span>
          <span className="text-sm">{value}</span>
        </div>
      ))}
    </div>
  );
}

function InputFilesSection({ agentId }: { agentId: string }) {
  const query = trpc.getAgentInputFiles.useQuery({ id: agentId });
  const [selectedFile, setSelectedFile] = useState<string | null>(null);

  useEffect(() => {
    setSelectedFile(null);
  }, [agentId]);

  useEffect(() => {
    if (!query.data?.files) return;
    if (selectedFile !== null) return;
    const manifest = query.data.files.find(f => f.name === 'manifest.json');
    setSelectedFile(manifest?.name ?? query.data.files[0]?.name ?? null);
  }, [query.data?.files]);

  if (query.isLoading) {
    return (
      <div className="space-y-2">
        <Skeleton variant="line" />
        <Skeleton variant="line" />
        <Skeleton variant="line" />
      </div>
    );
  }

  if (query.isError) {
    return (
      <div className="space-y-2">
        <p className="text-sm text-destructive">{query.error.message}</p>
        <Button variant="outline" size="sm" onClick={() => void query.refetch()}>Retry</Button>
      </div>
    );
  }

  const data = query.data;
  if (!data) return null;

  if (data.reason === 'worktree_missing') {
    return <p className="text-sm text-muted-foreground">Worktree no longer exists — input files unavailable</p>;
  }

  if (data.reason === 'input_dir_missing') {
    return <p className="text-sm text-muted-foreground">Input directory not found — this agent may not have received input files</p>;
  }

  const { files } = data;

  if (files.length === 0) {
    return <p className="text-sm text-muted-foreground">No input files found</p>;
  }

  return (
    <div className="flex flex-col md:flex-row gap-2 min-h-0">
      {/* File list */}
      <div className="md:w-48 shrink-0 overflow-y-auto space-y-0.5">
        {files.map(file => (
          <button
            key={file.name}
            onClick={() => setSelectedFile(file.name)}
            className={cn(
              "w-full text-left px-2 py-1 text-xs rounded truncate",
              selectedFile === file.name
                ? "bg-muted font-medium"
                : "hover:bg-muted/50 text-muted-foreground"
            )}
          >
            {file.name}
          </button>
        ))}
      </div>
      {/* Content pane */}
      <pre className="flex-1 text-xs font-mono overflow-auto bg-terminal rounded p-3 min-h-0">
        {files.find(f => f.name === selectedFile)?.content ?? ''}
      </pre>
    </div>
  );
}

function EffectivePromptSection({ agentId }: { agentId: string }) {
  const query = trpc.getAgentPrompt.useQuery({ id: agentId });

  if (query.isLoading) {
    return <Skeleton variant="rect" className="h-32 w-full" />;
  }

  if (query.isError) {
    return (
      <div className="space-y-2">
        <p className="text-sm text-destructive">{query.error.message}</p>
        <Button variant="outline" size="sm" onClick={() => void query.refetch()}>Retry</Button>
      </div>
    );
  }

  const data = query.data;
  if (!data) return null;

  if (data.reason === 'prompt_not_written') {
    return <p className="text-sm text-muted-foreground">Prompt file not available — agent may have been spawned before this feature was added</p>;
  }

  if (data.content) {
    return (
      <pre className="text-xs font-mono overflow-y-auto max-h-[400px] bg-terminal rounded p-3 whitespace-pre-wrap">
        {data.content}
      </pre>
    );
  }

  return null;
}
