import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  Activity,
  Bot,
  CheckCircle2,
  ChevronRight,
  PencilLine,
  PlayCircle,
  RotateCcw,
  Search,
  Settings2,
  Wrench,
} from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { aiAgentService } from "@/services/aiAgent.service";
import type {
  AIAgent,
  AIAgentSummary,
  AIAgentTestResponse,
  AIAgentUpdateInput,
  AIToolSummary,
} from "@/types/aiAgent";

const MODEL_OPTIONS = [
  { value: "gpt-4o", label: "GPT-4o (quality)" },
  { value: "gpt-4o-mini", label: "GPT-4o mini (cheap / fast)" },
  { value: "gpt-4.1", label: "GPT-4.1" },
  { value: "gpt-4.1-mini", label: "GPT-4.1 mini" },
  { value: "gpt-3.5-turbo", label: "GPT-3.5 turbo (legacy)" },
];

const GRAPH_OPTIONS = [
  { value: "simple", labelKey: "agents.graph.simple" },
  { value: "plan_review_revise", labelKey: "agents.graph.planReviewRevise" },
  { value: "rag", labelKey: "agents.graph.rag" },
  { value: "react", labelKey: "agents.graph.react" },
];

function GraphTypeBadge({ value }: { value: string }) {
  const { t } = useTranslation();
  const text = t(`agents.graph.${value === "plan_review_revise" ? "planReviewRevise" : value}`, value);
  const tone =
    value === "react"
      ? "bg-purple-500"
      : value === "rag"
      ? "bg-blue-500"
      : value === "plan_review_revise"
      ? "bg-emerald-500"
      : "bg-slate-500";
  return <Badge className={`${tone} text-white hover:${tone}`}>{text}</Badge>;
}

// ============================================================================
// Agent list (left rail)
// ============================================================================
function AgentsList({
  agents,
  selectedId,
  onSelect,
  isLoading,
  search,
  onSearch,
}: {
  agents: AIAgentSummary[];
  selectedId: number | null;
  onSelect: (id: number) => void;
  isLoading: boolean;
  search: string;
  onSearch: (v: string) => void;
}) {
  const { t } = useTranslation();
  return (
    <Card className="lg:col-span-1">
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <Bot className="h-4 w-4" />
          {t("agents.list.title", "Agents")}
        </CardTitle>
        <CardDescription>
          {t(
            "agents.list.subtitle",
            "Pre-configured for every platform pillar — edit defaults below.",
          )}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-2">
        <div className="relative">
          <Search className="text-muted-foreground absolute start-2 top-1/2 h-4 w-4 -translate-y-1/2" />
          <Input
            value={search}
            onChange={(e) => onSearch(e.target.value)}
            placeholder={t("agents.list.search", "Search agents…")}
            className="ps-8"
          />
        </div>
        {isLoading ? (
          <Skeleton className="h-64 w-full" />
        ) : agents.length === 0 ? (
          <p className="text-muted-foreground py-6 text-center text-sm">
            {t("agents.list.empty", "No agents match your search.")}
          </p>
        ) : (
          <ScrollArea className="h-[480px] pe-2">
            <ul className="space-y-1">
              {agents.map((a) => {
                const active = selectedId === a.id;
                return (
                  <li key={a.id}>
                    <button
                      type="button"
                      onClick={() => onSelect(a.id)}
                      className={`w-full rounded-md border p-3 text-start transition-colors ${
                        active
                          ? "border-primary bg-primary/5"
                          : "hover:bg-muted/40 border-transparent"
                      }`}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0 flex-1">
                          <div className="truncate text-sm font-medium">{a.name}</div>
                          <div className="text-muted-foreground truncate font-mono text-xs">
                            {a.key}
                          </div>
                        </div>
                        <ChevronRight className="text-muted-foreground h-4 w-4 flex-shrink-0" />
                      </div>
                      <div className="mt-2 flex flex-wrap items-center gap-1.5">
                        <GraphTypeBadge value={a.graph_type} />
                        <Badge variant="outline" className="text-xs">
                          {a.model}
                        </Badge>
                        <Badge variant="outline" className="text-xs">
                          <Wrench className="me-1 h-3 w-3" />
                          {a.tool_count}
                        </Badge>
                        {!a.active ? (
                          <Badge variant="secondary" className="text-xs">
                            {t("common.disabled", "Disabled")}
                          </Badge>
                        ) : null}
                      </div>
                    </button>
                  </li>
                );
              })}
            </ul>
          </ScrollArea>
        )}
      </CardContent>
    </Card>
  );
}

// ============================================================================
// Test panel (run a small input through the agent)
// ============================================================================
function AgentTestRunner({ agent }: { agent: AIAgent }) {
  const { t } = useTranslation();
  const [variables, setVariables] = useState<string>("{}");
  const [payload, setPayload] = useState<string>("");
  const [result, setResult] = useState<AIAgentTestResponse | null>(null);

  const test = useMutation({
    mutationFn: async () => {
      let parsedVars: Record<string, unknown> = {};
      try {
        parsedVars = variables.trim() ? JSON.parse(variables) : {};
      } catch {
        throw new Error(t("agents.test.badVarsJson", "Variables must be valid JSON."));
      }
      let parsedPayload: unknown = payload;
      const trimmed = payload.trim();
      if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
        try {
          parsedPayload = JSON.parse(trimmed);
        } catch {
          parsedPayload = payload;
        }
      }
      return aiAgentService.test(agent.id, {
        variables: parsedVars,
        payload: parsedPayload,
      });
    },
    onSuccess: (res) => {
      setResult(res);
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success(t("agents.test.ok", "Agent ran successfully"));
      }
    },
    onError: (err: Error) => toast.error(err.message),
  });

  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <PlayCircle className="h-4 w-4" />
          {t("agents.test.title", "Test runner")}
        </CardTitle>
        <CardDescription>
          {t(
            "agents.test.subtitle",
            "Send a small payload and inspect the agent's output, tool calls, and quality issues.",
          )}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="grid gap-3 md:grid-cols-2">
          <div className="space-y-1">
            <Label className="text-xs">
              {t("agents.test.variables", "Variables (JSON)")}
            </Label>
            <Textarea
              value={variables}
              onChange={(e) => setVariables(e.target.value)}
              placeholder='{"cefr_level": "b1"}'
              className="min-h-[120px] font-mono text-xs"
            />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">
              {t("agents.test.payload", "Payload (text or JSON)")}
            </Label>
            <Textarea
              value={payload}
              onChange={(e) => setPayload(e.target.value)}
              placeholder={t(
                "agents.test.payloadPlaceholder",
                "What should the agent do? e.g. 'Generate 5 MCQ for B1 reading.'",
              )}
              className="min-h-[120px] text-sm"
            />
          </div>
        </div>
        <Button onClick={() => test.mutate()} disabled={test.isPending}>
          <PlayCircle className="me-1 h-4 w-4" />
          {test.isPending
            ? t("agents.test.running", "Running…")
            : t("agents.test.run", "Run agent")}
        </Button>
        {result ? (
          <div className="space-y-3">
            <div className="flex flex-wrap gap-2 text-xs">
              <Badge variant="outline">
                <Activity className="me-1 h-3 w-3" />
                {t("agents.test.iterations", "Iterations")}: {result.iterations}
              </Badge>
              <Badge variant="outline">
                <RotateCcw className="me-1 h-3 w-3" />
                {t("agents.test.revisions", "Revisions")}: {result.revisions_used}
              </Badge>
              <Badge variant="outline">
                {t("agents.test.toolCalls", "Tool calls")}: {result.tool_results.length}
              </Badge>
              <Badge variant="outline">
                {t("agents.test.retrievalHits", "Retrieval hits")}: {result.retrieval_hits}
              </Badge>
              {result.quality_issues.length ? (
                <Badge className="bg-amber-500 text-white hover:bg-amber-500">
                  {t("agents.test.qualityIssues", "Quality issues")}: {result.quality_issues.length}
                </Badge>
              ) : null}
            </div>
            <div className="space-y-1">
              <Label className="text-xs uppercase tracking-wide">
                {t("agents.test.output", "Output")}
              </Label>
              <pre className="bg-muted/50 max-h-[300px] overflow-auto rounded-md p-3 text-xs">
                {typeof result.output === "string"
                  ? result.output
                  : JSON.stringify(result.output, null, 2)}
              </pre>
            </div>
            {result.tool_results.length ? (
              <details className="rounded-md border p-2">
                <summary className="cursor-pointer text-xs font-medium">
                  {t("agents.test.toolTrace", "Tool trace")}
                </summary>
                <pre className="mt-2 max-h-[260px] overflow-auto text-xs">
                  {JSON.stringify(result.tool_results, null, 2)}
                </pre>
              </details>
            ) : null}
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}

// ============================================================================
// Configure dialog
// ============================================================================
function ConfigureAgentDialog({
  agent,
  tools,
  open,
  onOpenChange,
}: {
  agent: AIAgent;
  tools: AIToolSummary[];
  open: boolean;
  onOpenChange: (v: boolean) => void;
}) {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const [draft, setDraft] = useState<AIAgentUpdateInput>({});

  useEffect(() => {
    if (open) {
      setDraft({
        name: agent.name,
        description: agent.description,
        system_prompt: agent.system_prompt,
        prompt_key: agent.prompt_key,
        model: agent.model,
        fallback_model: agent.fallback_model,
        temperature: agent.temperature,
        max_tokens: agent.max_tokens,
        max_revisions: agent.max_revisions,
        response_format: agent.response_format,
        graph_type: agent.graph_type,
        quality_checks: (agent.quality_checks || []).join(","),
        tool_keys: agent.tool_keys,
        active: agent.active,
      });
    }
  }, [open, agent]);

  const update = useMutation({
    mutationFn: (input: AIAgentUpdateInput) => aiAgentService.update(agent.id, input),
    onSuccess: () => {
      toast.success(t("agents.config.saved", "Agent configuration saved"));
      qc.invalidateQueries({ queryKey: ["ai-agents"] });
      qc.invalidateQueries({ queryKey: ["ai-agent", agent.id] });
      onOpenChange(false);
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const toggleTool = (key: string) => {
    const current = new Set(draft.tool_keys ?? []);
    if (current.has(key)) current.delete(key);
    else current.add(key);
    setDraft({ ...draft, tool_keys: Array.from(current) });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {t("agents.config.title", "Configure")} — {agent.name}
          </DialogTitle>
          <DialogDescription className="font-mono text-xs">
            {agent.key}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-2">
          {/* Identity */}
          <div className="grid gap-3 md:grid-cols-2">
            <div className="space-y-1">
              <Label className="text-xs">{t("agents.config.name", "Display name")}</Label>
              <Input
                value={draft.name ?? ""}
                onChange={(e) => setDraft({ ...draft, name: e.target.value })}
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">
                {t("agents.config.promptKey", "Prompt key (versioned)")}
              </Label>
              <Input
                value={draft.prompt_key ?? ""}
                placeholder="e.g. course_planner.system"
                onChange={(e) => setDraft({ ...draft, prompt_key: e.target.value })}
              />
            </div>
          </div>
          <div className="space-y-1">
            <Label className="text-xs">{t("agents.config.description", "Description")}</Label>
            <Textarea
              value={draft.description ?? ""}
              onChange={(e) => setDraft({ ...draft, description: e.target.value })}
              className="min-h-[60px]"
            />
          </div>
          <div className="space-y-1">
            <Label className="text-xs">{t("agents.config.systemPrompt", "System prompt")}</Label>
            <Textarea
              value={draft.system_prompt ?? ""}
              onChange={(e) => setDraft({ ...draft, system_prompt: e.target.value })}
              className="min-h-[200px] font-mono text-xs"
            />
            <p className="text-muted-foreground text-xs">
              {t(
                "agents.config.systemPromptHint",
                "If a prompt key is set above, the active version of that prompt overrides this field at runtime.",
              )}
            </p>
          </div>

          {/* Runtime config */}
          <div className="grid gap-3 md:grid-cols-3">
            <div className="space-y-1">
              <Label className="text-xs">{t("agents.config.model", "Model")}</Label>
              <Select
                value={draft.model ?? agent.model}
                onValueChange={(v) => setDraft({ ...draft, model: v })}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {MODEL_OPTIONS.map((m) => (
                    <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">
                {t("agents.config.fallbackModel", "Fallback model")}
              </Label>
              <Select
                value={draft.fallback_model ?? agent.fallback_model}
                onValueChange={(v) => setDraft({ ...draft, fallback_model: v })}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {MODEL_OPTIONS.map((m) => (
                    <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">{t("agents.config.responseFormat", "Output format")}</Label>
              <Select
                value={draft.response_format ?? agent.response_format}
                onValueChange={(v) =>
                  setDraft({ ...draft, response_format: v as "text" | "json" })
                }
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="json">JSON</SelectItem>
                  <SelectItem value="text">{t("agents.config.text", "Text")}</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">
                {t("agents.config.temperature", "Temperature")}
              </Label>
              <Input
                type="number"
                step="0.1"
                min={0}
                max={2}
                value={draft.temperature ?? agent.temperature}
                onChange={(e) =>
                  setDraft({ ...draft, temperature: Number(e.target.value) })
                }
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">
                {t("agents.config.maxTokens", "Max tokens")}
              </Label>
              <Input
                type="number"
                min={64}
                max={32000}
                value={draft.max_tokens ?? agent.max_tokens}
                onChange={(e) =>
                  setDraft({ ...draft, max_tokens: Number(e.target.value) })
                }
              />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">
                {t("agents.config.maxRevisions", "Max revisions")}
              </Label>
              <Input
                type="number"
                min={0}
                max={5}
                value={draft.max_revisions ?? agent.max_revisions}
                onChange={(e) =>
                  setDraft({ ...draft, max_revisions: Number(e.target.value) })
                }
              />
            </div>
          </div>

          {/* Graph */}
          <div className="space-y-1">
            <Label className="text-xs">
              {t("agents.config.graphType", "Graph topology")}
            </Label>
            <Select
              value={draft.graph_type ?? agent.graph_type}
              onValueChange={(v) =>
                setDraft({ ...draft, graph_type: v as AIAgent["graph_type"] })
              }
            >
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                {GRAPH_OPTIONS.map((g) => (
                  <SelectItem key={g.value} value={g.value}>
                    {t(g.labelKey, g.value)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1">
            <Label className="text-xs">
              {t("agents.config.qualityChecks", "Quality checks (comma-separated tool keys)")}
            </Label>
            <Input
              value={draft.quality_checks ?? ""}
              onChange={(e) =>
                setDraft({ ...draft, quality_checks: e.target.value })
              }
              placeholder="quality.cefr_check,quality.ai_detect"
              className="font-mono text-xs"
            />
          </div>

          {/* Tools */}
          <div className="space-y-2">
            <Label className="text-xs">{t("agents.config.tools", "Enabled tools")}</Label>
            <div className="grid gap-2 md:grid-cols-2">
              {tools.map((tool) => {
                const enabled = (draft.tool_keys ?? []).includes(tool.key);
                return (
                  <label
                    key={tool.id}
                    className={`flex items-start gap-2 rounded-md border p-2 text-xs transition-colors ${
                      enabled ? "border-primary bg-primary/5" : ""
                    }`}
                  >
                    <Checkbox
                      checked={enabled}
                      onCheckedChange={() => toggleTool(tool.key)}
                      className="mt-0.5"
                    />
                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-1">
                        <span className="font-mono text-xs">{tool.key}</span>
                        <Badge variant="outline" className="text-[10px] uppercase">
                          {tool.category}
                        </Badge>
                        {tool.mutates ? (
                          <Badge className="bg-amber-500 text-white hover:bg-amber-500 text-[10px]">
                            {t("agents.config.mutates", "writes")}
                          </Badge>
                        ) : null}
                      </div>
                      <p className="text-muted-foreground mt-0.5 line-clamp-2">
                        {tool.description}
                      </p>
                    </div>
                  </label>
                );
              })}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Switch
              checked={draft.active ?? agent.active}
              onCheckedChange={(v) => setDraft({ ...draft, active: v })}
            />
            <Label className="text-xs">
              {t("agents.config.active", "Agent is active")}
            </Label>
          </div>
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            {t("common.cancel", "Cancel")}
          </Button>
          <Button onClick={() => update.mutate(draft)} disabled={update.isPending}>
            <CheckCircle2 className="me-1 h-4 w-4" />
            {update.isPending
              ? t("common.saving", "Saving…")
              : t("common.save", "Save changes")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ============================================================================
// Detail panel
// ============================================================================
function AgentDetail({ agent, tools }: { agent: AIAgent; tools: AIToolSummary[] }) {
  const { t } = useTranslation();
  const [configOpen, setConfigOpen] = useState(false);
  return (
    <div className="space-y-4 lg:col-span-2">
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between gap-3">
            <div>
              <CardTitle className="text-xl">{agent.name}</CardTitle>
              <CardDescription className="font-mono text-xs">
                {agent.key}
              </CardDescription>
              {agent.description ? (
                <p className="mt-2 text-sm">{agent.description}</p>
              ) : null}
            </div>
            <Button variant="outline" onClick={() => setConfigOpen(true)}>
              <Settings2 className="me-1 h-4 w-4" />
              {t("agents.detail.configure", "Configure")}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 gap-3 text-sm md:grid-cols-4">
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.graph", "Graph")}
              </div>
              <div className="mt-1"><GraphTypeBadge value={agent.graph_type} /></div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.model", "Model")}
              </div>
              <div className="mt-1 font-mono text-sm">{agent.model}</div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.temperature", "Temperature")}
              </div>
              <div className="mt-1 font-mono text-sm">{agent.temperature.toFixed(2)}</div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.tokens", "Max tokens")}
              </div>
              <div className="mt-1 font-mono text-sm">{agent.max_tokens}</div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.format", "Output format")}
              </div>
              <div className="mt-1 text-sm">
                {agent.response_format === "json" ? "JSON" : t("agents.config.text", "Text")}
              </div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.fallback", "Fallback")}
              </div>
              <div className="mt-1 font-mono text-sm">
                {agent.fallback_model || "—"}
              </div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.revisions", "Max revisions")}
              </div>
              <div className="mt-1 font-mono text-sm">{agent.max_revisions}</div>
            </div>
            <div>
              <div className="text-muted-foreground text-xs">
                {t("agents.detail.promptKey", "Prompt key")}
              </div>
              <div className="mt-1 font-mono text-xs">
                {agent.prompt_key || "—"}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="flex items-center gap-2 text-base">
            <Wrench className="h-4 w-4" />
            {t("agents.detail.toolsTitle", "Enabled tools")} ({agent.tools.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {agent.tools.length === 0 ? (
            <p className="text-muted-foreground text-sm">
              {t("agents.detail.noTools", "This agent has no tools enabled.")}
            </p>
          ) : (
            <ul className="space-y-2">
              {agent.tools.map((tool) => (
                <li key={tool.id} className="rounded-md border p-2 text-sm">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="font-mono text-xs">{tool.key}</span>
                    <Badge variant="outline" className="text-[10px] uppercase">
                      {tool.category}
                    </Badge>
                    {tool.mutates ? (
                      <Badge className="bg-amber-500 text-white hover:bg-amber-500 text-[10px]">
                        {t("agents.config.mutates", "writes")}
                      </Badge>
                    ) : null}
                  </div>
                  <p className="text-muted-foreground mt-1 text-xs">{tool.description}</p>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="flex items-center gap-2 text-base">
            <PencilLine className="h-4 w-4" />
            {t("agents.detail.systemPrompt", "System prompt")}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <pre className="bg-muted/50 max-h-[260px] overflow-auto rounded-md p-3 text-xs">
            {agent.system_prompt || t("agents.detail.noPrompt", "(empty)")}
          </pre>
        </CardContent>
      </Card>

      <AgentTestRunner agent={agent} />

      <ConfigureAgentDialog
        agent={agent}
        tools={tools}
        open={configOpen}
        onOpenChange={setConfigOpen}
      />
    </div>
  );
}

// ============================================================================
// Top-level Agents tab
// ============================================================================
export function AIAgentsPanel() {
  const { t } = useTranslation();
  const [search, setSearch] = useState("");
  const [selectedId, setSelectedId] = useState<number | null>(null);

  const agentsQ = useQuery({
    queryKey: ["ai-agents", { search }],
    queryFn: () => aiAgentService.list(search ? { search } : undefined),
  });

  const toolsQ = useQuery({
    queryKey: ["ai-agent-tools"],
    queryFn: () => aiAgentService.listTools(),
  });

  // Auto-select first agent.
  useEffect(() => {
    if (!selectedId && agentsQ.data && agentsQ.data.length > 0) {
      setSelectedId(agentsQ.data[0].id);
    }
  }, [selectedId, agentsQ.data]);

  const detailQ = useQuery({
    queryKey: ["ai-agent", selectedId],
    queryFn: () => aiAgentService.get(selectedId as number),
    enabled: !!selectedId,
  });

  const filteredAgents = useMemo(() => agentsQ.data ?? [], [agentsQ.data]);

  return (
    <div className="grid gap-4 lg:grid-cols-3">
      <AgentsList
        agents={filteredAgents}
        selectedId={selectedId}
        onSelect={setSelectedId}
        isLoading={agentsQ.isLoading}
        search={search}
        onSearch={setSearch}
      />
      {detailQ.data ? (
        <AgentDetail agent={detailQ.data} tools={toolsQ.data ?? []} />
      ) : selectedId ? (
        <Card className="lg:col-span-2">
          <CardContent className="p-6">
            <Skeleton className="h-72 w-full" />
          </CardContent>
        </Card>
      ) : (
        <Card className="lg:col-span-2">
          <CardContent className="text-muted-foreground p-6 text-sm">
            {t("agents.detail.empty", "Select an agent to inspect its configuration.")}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
