import { useState } from "react";
import { createFileRoute, useNavigate, useSearch } from "@tanstack/react-router";
import { motion } from "motion/react";
import { AlertCircle, RefreshCw, Terminal, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/Skeleton";
import { toast } from "sonner";
import { trpc } from "@/lib/trpc";
import { AgentOutputViewer } from "@/components/AgentOutputViewer";
import { AgentActions } from "@/components/AgentActions";
import { formatRelativeTime } from "@/lib/utils";
import { modeLabel } from "@/lib/labels";
import { StatusDot } from "@/components/StatusDot";
import { useLiveUpdates } from "@/hooks";

type StatusFilter = "all" | "running" | "questions" | "exited" | "dismissed";
const STATUS_FILTERS = ["all", "running", "questions", "exited", "dismissed"] as const;

export const Route = createFileRoute("/agents")({
  component: AgentsPage,
  validateSearch: (search: Record<string, unknown>) => ({
    filter: STATUS_FILTERS.includes(search.filter as StatusFilter)
      ? (search.filter as StatusFilter)
      : "questions",
  }),
});

function AgentsPage() {
  const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
  const { filter } = useSearch({ from: "/agents" });
  const navigate = useNavigate();

  // Live updates
  const utils = trpc.useUtils();
  useLiveUpdates([
    { prefix: 'agent:', invalidate: ['listAgents'] },
  ]);

  // Data
  const agentsQuery = trpc.listAgents.useQuery();

  // Mutations
  const stopMutation = trpc.stopAgent.useMutation({
    onSuccess: (data) => {
      toast.success(`Stopped ${data.name}`);
    },
    onError: (err) => toast.error(`Failed to stop: ${err.message}`),
  });

  const deleteMutation = trpc.deleteAgent.useMutation({
    onSuccess: (data) => {
      if (selectedAgentId) {
        const deleted = agents.find(
          (a) => a.name === data.name || a.id === selectedAgentId
        );
        if (deleted) setSelectedAgentId(null);
      }
      toast.success(`Deleted ${data.name}`);
    },
    onError: (err) => toast.error(`Failed to delete: ${err.message}`),
  });

  const dismissMutation = trpc.dismissAgent.useMutation({
    onSuccess: (data) => {
      toast.success(`Dismissed ${data.name}`);
    },
    onError: (err) => toast.error(`Failed to dismiss: ${err.message}`),
  });

  // Handlers
  function handleRefresh() {
    void utils.listAgents.invalidate();
  }

  function handleStop(id: string) {
    stopMutation.mutate({ id });
  }

  function handleDelete(id: string) {
    if (!window.confirm("Delete this agent? This cannot be undone.")) return;
    setSelectedAgentId((prev) => (prev === id ? null : prev));
    deleteMutation.mutate({ id });
  }

  function handleDismiss(id: string) {
    dismissMutation.mutate({ id });
  }

  function handleGoToInbox() {
    void navigate({ to: "/inbox" });
  }

  // Loading state
  if (agentsQuery.isLoading) {
    return (
      <div className="flex h-full flex-col gap-4">
        <div className="flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2">
            <Skeleton className="h-6 w-20" />
            <Skeleton className="h-5 w-8 rounded-full" />
          </div>
          <Skeleton className="h-8 w-20" />
        </div>
        <div className="grid grid-cols-1 gap-4 lg:grid-cols-[320px_1fr] min-h-0 flex-1">
          <div className="space-y-2 overflow-y-auto min-h-0">
            {Array.from({ length: 5 }).map((_, i) => (
              <Card key={i} className="p-3">
                <div className="flex items-center gap-3">
                  <Skeleton className="h-2 w-2 rounded-full" />
                  <Skeleton className="h-4 w-24" />
                </div>
              </Card>
            ))}
          </div>
          <Skeleton className="h-full rounded-lg" />
        </div>
      </div>
    );
  }

  // Error state
  if (agentsQuery.isError) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 py-12">
        <AlertCircle className="h-8 w-8 text-destructive" />
        <p className="text-sm text-destructive">
          Failed to load agents:{" "}
          {agentsQuery.error?.message ?? "Unknown error"}
        </p>
        <Button variant="outline" size="sm" onClick={handleRefresh}>
          Retry
        </Button>
      </div>
    );
  }

  const agents = agentsQuery.data ?? [];
  const selectedAgent = selectedAgentId
    ? agents.find((a) => a.id === selectedAgentId)
    : null;

  // Filter counts
  const counts = {
    all: agents.filter((a) => !a.userDismissedAt).length,
    running: agents.filter((a) => a.status === "running").length,
    questions: agents.filter((a) => a.status === "waiting_for_input").length,
    exited: agents.filter((a) =>
      ["stopped", "crashed", "idle"].includes(a.status)
    ).length,
    dismissed: agents.filter((a) => a.userDismissedAt).length,
  };

  // Filter + sort
  const filtered = agents
    .filter((agent) => {
      switch (filter) {
        case "all":
          return !agent.userDismissedAt;
        case "running":
          return agent.status === "running";
        case "questions":
          return agent.status === "waiting_for_input";
        case "exited":
          return ["stopped", "crashed", "idle"].includes(agent.status);
        case "dismissed":
          return !!agent.userDismissedAt;
      }
    })
    .sort(
      (a, b) =>
        new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );

  const filterOptions: { value: StatusFilter; label: string }[] = [
    { value: "all", label: "All" },
    { value: "running", label: "Running" },
    { value: "questions", label: "Questions" },
    { value: "exited", label: "Exited" },
    { value: "dismissed", label: "Dismissed" },
  ];

  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, ease: [0, 0, 0.2, 1] }}
      className="flex h-full flex-col gap-4"
    >
      {/* Header + Filters */}
      <div className="shrink-0 space-y-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <h1 className="font-display text-lg font-semibold">Agents</h1>
            <Badge variant="secondary">{agents.length}</Badge>
          </div>
          <Button variant="outline" size="sm" onClick={handleRefresh}>
            <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
            Refresh
          </Button>
        </div>
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3, delay: 0.05, ease: [0, 0, 0.2, 1] }}
          className="flex items-center gap-1"
        >
          {filterOptions.map((opt) => (
            <Button
              key={opt.value}
              variant={filter === opt.value ? "default" : "outline"}
              size="sm"
              className="h-7 px-2 text-xs"
              onClick={() => navigate({ to: "/agents", search: { filter: opt.value } })}
            >
              {opt.label}
              <span className="ml-1.5 text-[10px] tabular-nums opacity-70">
                {counts[opt.value]}
              </span>
            </Button>
          ))}
        </motion.div>
      </div>

      {/* Two-panel layout */}
      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1, ease: [0, 0, 0.2, 1] }}
        className="grid grid-cols-1 gap-4 lg:grid-cols-[320px_1fr] min-h-0 flex-1"
      >
        {/* Left: Agent List */}
        <div className="overflow-y-auto min-h-0 space-y-2 lg:border-r lg:border-border/50 lg:pr-4">
          {filtered.length === 0 ? (
            <div className="flex flex-col items-center justify-center gap-3 rounded-lg border border-dashed p-12 text-center">
              <Users className="h-8 w-8 text-muted-foreground/40" />
              <div className="space-y-1">
                <p className="text-sm font-medium text-muted-foreground">No agents match this filter</p>
                <p className="text-xs text-muted-foreground/70">Try selecting a different filter above</p>
              </div>
            </div>
          ) : (
            filtered.map((agent, i) => (
              <motion.div
                key={agent.id}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{
                  duration: 0.3,
                  delay: Math.min(i * 0.05, 0.3),
                  ease: [0, 0, 0.2, 1],
                }}
              >
                <Card
                  interactive
                  selected={selectedAgentId === agent.id}
                  className="p-3"
                  onClick={() => setSelectedAgentId(agent.id)}
                >
                  <div className="flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2 min-w-0">
                      <StatusDot status={agent.status} size="sm" />
                      <span className="truncate text-sm font-medium">
                        {agent.name}
                      </span>
                    </div>
                    <div className="flex items-center gap-1.5 shrink-0">
                      <Badge variant="outline" className="text-xs">
                        {agent.provider}
                      </Badge>
                      <Badge variant="secondary" className="text-xs">
                        {modeLabel(agent.mode)}
                      </Badge>
                      {/* Action dropdown */}
                      <div onClick={(e) => e.stopPropagation()}>
                        <AgentActions
                          agentId={agent.id}
                          status={agent.status}
                          isDismissed={!!agent.userDismissedAt}
                          onStop={handleStop}
                          onDelete={handleDelete}
                          onDismiss={handleDismiss}
                          onGoToInbox={handleGoToInbox}
                        />
                      </div>
                    </div>
                  </div>
                  <div className="mt-1 flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">
                      {formatRelativeTime(String(agent.updatedAt))}
                    </span>
                    {agent.status === "waiting_for_input" && (
                      <span
                        className="text-xs text-status-warning-fg hover:underline cursor-pointer"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleGoToInbox();
                        }}
                      >
                        Answer questions &rarr;
                      </span>
                    )}
                  </div>
                </Card>
              </motion.div>
            ))
          )}
        </div>

        {/* Right: Output Viewer */}
        <div className="min-h-0 overflow-hidden">
          {selectedAgent ? (
            <AgentOutputViewer
              agentId={selectedAgent.id}
              agentName={selectedAgent.name}
              status={selectedAgent.status}
              onStop={handleStop}
            />
          ) : (
            <div className="flex h-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed">
              <Terminal className="h-10 w-10 text-muted-foreground/30" />
              <div className="space-y-1 text-center">
                <p className="text-sm font-medium text-muted-foreground">No agent selected</p>
                <p className="text-xs text-muted-foreground/70">Select an agent from the list to view output</p>
              </div>
            </div>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}
