import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Search, Wrench } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { aiAgentService } from "@/services/aiAgent.service";
import type { AIToolSummary } from "@/types/aiAgent";

const CATEGORY_TONES: Record<string, string> = {
  retrieval: "bg-blue-500",
  persistence: "bg-amber-500",
  quality: "bg-purple-500",
  scoring: "bg-emerald-500",
  reference: "bg-slate-500",
  other: "bg-zinc-500",
};

export function AIToolsPanel() {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const [search, setSearch] = useState("");

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

  const toggle = useMutation({
    mutationFn: (tool: AIToolSummary) =>
      aiAgentService.updateTool(tool.id, { active: !tool.active }),
    onSuccess: (tool) => {
      toast.success(
        tool.active
          ? t("tools.toggle.enabled", "Tool enabled")
          : t("tools.toggle.disabled", "Tool disabled"),
      );
      qc.invalidateQueries({ queryKey: ["ai-agent-tools"] });
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const filtered = useMemo(() => {
    const items = toolsQ.data ?? [];
    if (!search.trim()) return items;
    const needle = search.toLowerCase();
    return items.filter(
      (t) =>
        t.key.toLowerCase().includes(needle) ||
        t.name.toLowerCase().includes(needle) ||
        (t.description || "").toLowerCase().includes(needle),
    );
  }, [toolsQ.data, search]);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-base">
          <Wrench className="h-4 w-4" />
          {t("tools.title", "Agent tools")}
        </CardTitle>
        <CardDescription>
          {t(
            "tools.subtitle",
            "Capabilities your agents can call. Toggle a tool off to take it out of every agent without editing each one.",
          )}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="relative max-w-sm">
          <Search className="text-muted-foreground absolute start-2 top-1/2 h-4 w-4 -translate-y-1/2" />
          <Input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder={t("tools.search", "Search tools…")}
            className="ps-8"
          />
        </div>
        {toolsQ.isLoading ? (
          <Skeleton className="h-64 w-full" />
        ) : filtered.length === 0 ? (
          <p className="text-muted-foreground text-sm">
            {t("tools.empty", "No tools match your search.")}
          </p>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("tools.col.key", "Key")}</TableHead>
                <TableHead>{t("tools.col.name", "Name")}</TableHead>
                <TableHead>{t("tools.col.category", "Category")}</TableHead>
                <TableHead>{t("tools.col.description", "Description")}</TableHead>
                <TableHead>{t("tools.col.params", "Params")}</TableHead>
                <TableHead className="w-[100px] text-end">
                  {t("tools.col.active", "Active")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((tool) => {
                const tone = CATEGORY_TONES[tool.category] || "bg-zinc-500";
                const params =
                  (tool.schema?.properties as Record<string, unknown>) || {};
                const paramKeys = Object.keys(params);
                return (
                  <TableRow key={tool.id}>
                    <TableCell className="font-mono text-xs">{tool.key}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <span>{tool.name}</span>
                        {tool.mutates ? (
                          <Badge className="bg-amber-500 text-white text-[10px] hover:bg-amber-500">
                            {t("tools.writes", "writes")}
                          </Badge>
                        ) : null}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={`${tone} text-white hover:${tone}`}>
                        {tool.category}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground max-w-[360px] text-xs">
                      {tool.description}
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {paramKeys.length === 0 ? (
                          <span className="text-muted-foreground text-xs">—</span>
                        ) : (
                          paramKeys.slice(0, 5).map((k) => (
                            <Badge key={k} variant="outline" className="text-[10px]">
                              {k}
                            </Badge>
                          ))
                        )}
                        {paramKeys.length > 5 ? (
                          <Badge variant="outline" className="text-[10px]">
                            +{paramKeys.length - 5}
                          </Badge>
                        ) : null}
                      </div>
                    </TableCell>
                    <TableCell className="text-end">
                      <Switch
                        checked={tool.active}
                        onCheckedChange={() => toggle.mutate(tool)}
                        disabled={toggle.isPending}
                      />
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        )}
      </CardContent>
    </Card>
  );
}
