"use client";

import { useEffect, useState, useCallback } from "react";
import { api } from "@/app/adminx/admin-api";
import {
  Card,
  Button,
  Badge,
  Modal,
  Field,
  Input,
  Textarea,
  Select,
  Toggle,
  SectionTitle,
  ErrorNote,
} from "@/app/adminx/ui";

interface Provider {
  id: number;
  name: string;
  keySet?: boolean;
}
interface Tool {
  id: number;
  name: string;
  slug: string;
  icon: string;
  shortDescription: string;
  description: string;
  systemPrompt: string;
  placeholder: string;
  primaryProviderId: number | null;
  backupProviderId: number | null;
  model: string;
  temperature: number;
  maxTokens: number;
  maxResults: number;
  seoTitle: string;
  seoDescription: string;
  status: string;
  featured: boolean;
  sortOrder: number;
}

const empty: Tool = {
  id: 0,
  name: "",
  slug: "",
  icon: "✨",
  shortDescription: "",
  description: "",
  systemPrompt: "",
  placeholder: "",
  primaryProviderId: null,
  backupProviderId: null,
  model: "",
  temperature: 0.7,
  maxTokens: 1024,
  maxResults: 5,
  seoTitle: "",
  seoDescription: "",
  status: "enabled",
  featured: true,
  sortOrder: 0,
};

export function ToolsSection() {
  const [tools, setTools] = useState<Tool[]>([]);
  const [providers, setProviders] = useState<Provider[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [editing, setEditing] = useState<Tool | null>(null);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    try {
      const data = await api.get("tools");
      setTools(data.tools);
      setProviders(data.providers);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function save() {
    if (!editing) return;
    setSaving(true);
    setError("");
    try {
      if (editing.id) {
        await api.put(`tools?id=${editing.id}`, editing);
      } else {
        await api.post("tools", editing);
      }
      setEditing(null);
      await load();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setSaving(false);
    }
  }

  async function toggle(t: Tool, field: "status" | "featured") {
    const updated = {
      ...t,
      [field]: field === "status" ? (t.status === "enabled" ? "disabled" : "enabled") : !t.featured,
    };
    await api.put(`tools?id=${t.id}`, updated);
    await load();
  }

  async function remove(t: Tool) {
    if (!confirm(`Delete "${t.name}"?`)) return;
    await api.del(`tools?id=${t.id}`);
    await load();
  }

  const set = (patch: Partial<Tool>) => setEditing((e) => (e ? { ...e, ...patch } : e));

  if (loading) return <p className="text-slate-500">Loading…</p>;

  return (
    <div>
      <SectionTitle
        title="AI Tools"
        action={
          <Button onClick={() => setEditing({ ...empty, sortOrder: tools.length + 1 })}>+ New Tool</Button>
        }
      />

      <ErrorNote message={error} />

      <Card className="overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="border-b border-slate-100 bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
              <tr>
                <th className="px-4 py-3">Tool</th>
                <th className="px-4 py-3">Slug</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Featured</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {tools.map((t) => (
                <tr key={t.id} className="border-b border-slate-50 hover:bg-slate-50/50">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <span className="text-xl">{t.icon}</span>
                      <span className="font-medium text-slate-800">{t.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-slate-500">/{t.slug}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => toggle(t, "status")}>
                      <Badge color={t.status === "enabled" ? "green" : "slate"}>
                        {t.status}
                      </Badge>
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <Toggle checked={t.featured} onChange={() => toggle(t, "featured")} />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-1">
                      <Button variant="ghost" onClick={() => setEditing(t)}>Edit</Button>
                      <Button variant="ghost" onClick={() => remove(t)} className="text-red-600 hover:bg-red-50">Delete</Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      <Modal open={!!editing} onClose={() => setEditing(null)} title={editing?.id ? "Edit Tool" : "New Tool"} wide>
        {editing && (
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <Field label="Name">
              <Input value={editing.name} onChange={(e) => set({ name: e.target.value })} />
            </Field>
            <Field label="Slug" hint="URL-safe, auto-generated if empty">
              <Input value={editing.slug} onChange={(e) => set({ slug: e.target.value })} />
            </Field>
            <Field label="Icon (emoji)">
              <Input value={editing.icon} onChange={(e) => set({ icon: e.target.value })} />
            </Field>
            <Field label="Sort order">
              <Input type="number" value={editing.sortOrder} onChange={(e) => set({ sortOrder: Number(e.target.value) })} />
            </Field>
            <div className="sm:col-span-2">
              <Field label="Short description">
                <Input value={editing.shortDescription} onChange={(e) => set({ shortDescription: e.target.value })} />
              </Field>
            </div>
            <div className="sm:col-span-2">
              <Field label="Full description">
                <Textarea rows={2} value={editing.description} onChange={(e) => set({ description: e.target.value })} />
              </Field>
            </div>
            <div className="sm:col-span-2">
              <Field label="System prompt" hint="Instructions sent to the AI. Output should be one result per line.">
                <Textarea rows={4} value={editing.systemPrompt} onChange={(e) => set({ systemPrompt: e.target.value })} />
              </Field>
            </div>
            <div className="sm:col-span-2">
              <Field label="Placeholder">
                <Input value={editing.placeholder} onChange={(e) => set({ placeholder: e.target.value })} />
              </Field>
            </div>
            <Field label="Primary provider">
              <Select value={editing.primaryProviderId ?? ""} onChange={(e) => set({ primaryProviderId: e.target.value ? Number(e.target.value) : null })}>
                <option value="">Default</option>
                {providers.map((p) => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </Select>
            </Field>
            <Field label="Backup provider">
              <Select value={editing.backupProviderId ?? ""} onChange={(e) => set({ backupProviderId: e.target.value ? Number(e.target.value) : null })}>
                <option value="">None</option>
                {providers.map((p) => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </Select>
            </Field>
            <Field label="Model override" hint="Leave empty to use provider model">
              <Input value={editing.model} onChange={(e) => set({ model: e.target.value })} />
            </Field>
            <Field label="Temperature">
              <Input type="number" step="0.1" value={editing.temperature} onChange={(e) => set({ temperature: Number(e.target.value) })} />
            </Field>
            <Field label="Max tokens">
              <Input type="number" value={editing.maxTokens} onChange={(e) => set({ maxTokens: Number(e.target.value) })} />
            </Field>
            <Field label="Max results">
              <Input type="number" value={editing.maxResults} onChange={(e) => set({ maxResults: Number(e.target.value) })} />
            </Field>
            <div className="sm:col-span-2">
              <Field label="SEO title">
                <Input value={editing.seoTitle} onChange={(e) => set({ seoTitle: e.target.value })} />
              </Field>
            </div>
            <div className="sm:col-span-2">
              <Field label="SEO description">
                <Textarea rows={2} value={editing.seoDescription} onChange={(e) => set({ seoDescription: e.target.value })} />
              </Field>
            </div>
            <div className="sm:col-span-2 flex flex-wrap gap-6">
              <Toggle checked={editing.status === "enabled"} onChange={(v) => set({ status: v ? "enabled" : "disabled" })} label="Enabled" />
              <Toggle checked={editing.featured} onChange={(v) => set({ featured: v })} label="Show on homepage" />
            </div>
            <div className="sm:col-span-2 flex justify-end gap-2">
              <Button variant="secondary" onClick={() => setEditing(null)}>Cancel</Button>
              <Button onClick={save} disabled={saving || !editing.name}>{saving ? "Saving…" : "Save Tool"}</Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
