"use client";

import * as React from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "@/lib/api";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Search, Globe, FileText, Loader2, Check, AlertTriangle, Wrench } from "lucide-react";
import { toast } from "sonner";

interface MeResponse {
  user: {
    searxngUrl: string;
    toolsEnabled: boolean;
    enabledTools: string;
    maxToolIterations: number;
  };
}

const TOOL_META: { name: string; label: string; description: string; icon: React.ReactNode }[] = [
  {
    name: "rechercher_web",
    label: "Recherche web (SearXNG)",
    description: "Recherche web via votre instance SearXNG.",
    icon: <Search className="h-4 w-4" />,
  },
  {
    name: "lire_page",
    label: "Lecture de page",
    description: "Récupère et nettoie le contenu d'une URL publique.",
    icon: <Globe className="h-4 w-4" />,
  },
  {
    name: "creer_pdf",
    label: "Génération PDF",
    description: "Convertit du markdown en PDF stylisé (puppeteer).",
    icon: <FileText className="h-4 w-4" />,
  },
];

export function ToolsSettings() {
  const qc = useQueryClient();
  const meQuery = useQuery({
    queryKey: ["me"],
    queryFn: () => apiFetch<MeResponse>("/api/me"),
  });
  const me = meQuery.data?.user;

  const [searxngUrl, setSearxngUrl] = React.useState("");
  const [toolsEnabled, setToolsEnabled] = React.useState(true);
  const [enabledTools, setEnabledTools] = React.useState<string[]>([]);
  const [maxIter, setMaxIter] = React.useState(10);
  const [testing, setTesting] = React.useState(false);
  const [testResult, setTestResult] = React.useState<{ ok: boolean; error?: string; count?: number } | null>(null);

  React.useEffect(() => {
    if (!me) return;
    setSearxngUrl(me.searxngUrl);
    setToolsEnabled(me.toolsEnabled);
    setEnabledTools(
      (me.enabledTools || "")
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean),
    );
    setMaxIter(me.maxToolIterations);
  }, [me]);

  const save = useMutation({
    mutationFn: () =>
      apiFetch("/api/me", {
        method: "PATCH",
        body: JSON.stringify({
          searxngUrl,
          toolsEnabled,
          enabledTools: enabledTools.join(","),
          maxToolIterations: maxIter,
        }),
      }),
    onSuccess: () => {
      toast.success("Settings saved");
      qc.invalidateQueries({ queryKey: ["me"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  async function testSearxng() {
    setTesting(true);
    setTestResult(null);
    try {
      const u = `${searxngUrl.replace(/\/+$/, "")}/search?q=hello&format=json`;
      const res = await fetch(u);
      if (!res.ok) {
        setTestResult({ ok: false, error: `HTTP ${res.status}` });
        return;
      }
      const data = (await res.json()) as { results?: unknown[] };
      setTestResult({ ok: true, count: data.results?.length ?? 0 });
    } catch (e) {
      setTestResult({ ok: false, error: e instanceof Error ? e.message : "Failed" });
    } finally {
      setTesting(false);
    }
  }

  function toggleTool(name: string, on: boolean) {
    setEnabledTools((prev) => {
      const set = new Set(prev);
      if (on) set.add(name);
      else set.delete(name);
      return [...set];
    });
  }

  if (!me) return <div className="p-4 text-sm text-muted-foreground">Loading…</div>;

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Wrench className="h-4 w-4" />
            Agent tools
          </CardTitle>
          <CardDescription>
            Donne au modèle l&apos;accès à la recherche web, à la lecture de pages, et à la
            génération de PDF. Demande un modèle compatible (capacité <code>tools</code>).
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between rounded-lg border border-border px-4 py-3">
            <div>
              <Label>Activer les outils</Label>
              <p className="text-xs text-muted-foreground">
                Master toggle. Désactivé, l&apos;assistant répond sans outils.
              </p>
            </div>
            <Switch checked={toolsEnabled} onCheckedChange={setToolsEnabled} />
          </div>

          <div className="space-y-2">
            <Label>Outils disponibles</Label>
            <div className="divide-y divide-border rounded-lg border border-border">
              {TOOL_META.map((t) => (
                <div key={t.name} className="flex items-center justify-between gap-3 px-4 py-3">
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 text-muted-foreground">{t.icon}</div>
                    <div>
                      <div className="text-sm font-medium">{t.label}</div>
                      <div className="text-xs text-muted-foreground">{t.description}</div>
                    </div>
                  </div>
                  <Switch
                    checked={enabledTools.includes(t.name)}
                    onCheckedChange={(v) => toggleTool(t.name, v)}
                    disabled={!toolsEnabled}
                  />
                </div>
              ))}
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="searx">SearXNG URL</Label>
            <div className="flex gap-2">
              <Input
                id="searx"
                value={searxngUrl}
                onChange={(e) => setSearxngUrl(e.target.value)}
                placeholder="http://localhost:8888"
              />
              <Button variant="secondary" onClick={testSearxng} disabled={testing || !searxngUrl}>
                {testing ? <Loader2 className="animate-spin" /> : "Test"}
              </Button>
            </div>
            {testResult && (
              <p
                className={
                  testResult.ok
                    ? "flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400"
                    : "flex items-center gap-1 text-xs text-destructive"
                }
              >
                {testResult.ok ? <Check className="h-3 w-3" /> : <AlertTriangle className="h-3 w-3" />}
                {testResult.ok
                  ? `OK — ${testResult.count} résultats sur "hello"`
                  : testResult.error}
              </p>
            )}
            <p className="text-xs text-muted-foreground">
              Active le format JSON dans <code>settings.yml</code> de SearXNG (
              <code>formats: [html, json]</code>).
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="maxiter">Itérations max d&apos;outils par message</Label>
            <Input
              id="maxiter"
              type="number"
              min={1}
              max={25}
              value={maxIter}
              onChange={(e) => setMaxIter(Number(e.target.value) || 1)}
            />
            <p className="text-xs text-muted-foreground">
              Au-delà de cette limite, la boucle s&apos;arrête et un avertissement s&apos;affiche.
            </p>
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-end">
        <Button onClick={() => save.mutate()} disabled={save.isPending}>
          {save.isPending ? "Saving…" : "Save changes"}
        </Button>
      </div>
    </div>
  );
}
