"use client";

import { useState, useTransition } from "react";

interface PluginRow {
  key: string;
  name: string;
  description: string;
  category: string;
  version: string;
  enabled: boolean;
  config: Record<string, unknown>;
}

const CATEGORY_LABEL: Record<string, string> = {
  visual: "Visuels",
  business: "Métier",
  content: "Contenus",
  i18n: "Internationalisation",
  core: "Core",
};

export default function PluginToggleTable({ plugins: initial }: { plugins: PluginRow[] }) {
  const [plugins, setPlugins] = useState(initial);
  const [pending, startTransition] = useTransition();
  const [busyKey, setBusyKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const byCategory = plugins.reduce<Record<string, PluginRow[]>>((acc, p) => {
    (acc[p.category] ??= []).push(p);
    return acc;
  }, {});

  async function toggle(key: string, next: boolean) {
    setError(null);
    setBusyKey(key);
    try {
      const res = await fetch(`/api/admin/plugins/${encodeURIComponent(key)}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ enabled: next }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body?.error || `HTTP ${res.status}`);
      }
      const updated = await res.json();
      startTransition(() => {
        setPlugins((curr) =>
          curr.map((p) => (p.key === key ? { ...p, enabled: !!updated.enabled } : p)),
        );
      });
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setBusyKey(null);
    }
  }

  return (
    <div className="space-y-8">
      {error && (
        <div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700">
          {error}
        </div>
      )}
      {Object.entries(byCategory).map(([category, rows]) => (
        <section key={category}>
          <h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">
            {CATEGORY_LABEL[category] ?? category}
          </h2>
          <ul className="divide-y divide-gray-200 rounded-lg border border-gray-200 bg-white">
            {rows.map((p) => (
              <li key={p.key} className="flex items-start justify-between gap-4 px-4 py-3">
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-gray-900">{p.name}</span>
                    <code className="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600">{p.key}</code>
                    <span className="text-xs text-gray-400">v{p.version}</span>
                  </div>
                  <p className="mt-1 text-sm text-gray-600">{p.description}</p>
                </div>
                <button
                  type="button"
                  onClick={() => toggle(p.key, !p.enabled)}
                  disabled={pending || busyKey === p.key}
                  className={`shrink-0 rounded-full px-3 py-1 text-xs font-semibold transition ${
                    p.enabled
                      ? "bg-green-600 text-white hover:bg-green-700"
                      : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                  } disabled:opacity-50`}
                >
                  {busyKey === p.key ? "…" : p.enabled ? "Activé" : "Désactivé"}
                </button>
              </li>
            ))}
          </ul>
        </section>
      ))}
    </div>
  );
}
