"use client";

import { useEffect, useState } from "react";
import { get, put } from "@/lib/api";
import { Badge, Field, Notice, Spinner } from "@/components/ui";

type AgGridStatus = { licenseKey: string; licenseKeySet: boolean };

export default function AgGridSettings() {
  const [data, setData] = useState<AgGridStatus | null>(null);
  const [licenseKey, setLicenseKey] = useState("");
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);

  useEffect(() => {
    get<AgGridStatus>("ag-grid")
      .then((d) => {
        setData(d);
        setLicenseKey(d.licenseKey);
      })
      .catch((e) => setLoadError((e as Error).message));
  }, []);

  if (loadError) return <Notice kind="error">Could not load AG Grid config: {loadError}</Notice>;
  if (!data) return <Spinner label="Loading AG Grid configuration…" />;

  async function save(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBusy(true);
    setSaved(false);
    try {
      const d = await put<AgGridStatus>("ag-grid", { licenseKey });
      setData(d);
      setLicenseKey(d.licenseKey);
      setSaved(true);
    } finally {
      setBusy(false);
    }
  }

  return (
    <section aria-labelledby="aggrid-h" className="space-y-6">
      <h2 id="aggrid-h" className="text-xl font-semibold text-slate-900">AG Grid Enterprise</h2>
      <p className="-mt-4 text-sm text-slate-600">
        The data tables use AG Grid Enterprise. Paste your license key to unlock the premium features and remove the
        “license required” watermark. The grids work without a key (watermarked).
      </p>

      {saved && <Notice kind="success">AG Grid license saved. Reload to apply it everywhere.</Notice>}

      <form onSubmit={save} className="space-y-4">
        <div className="card">
          <Field
            label="License key"
            htmlFor="aggrid-key"
            hint="From your AG Grid Enterprise subscription. Stored in the config store; applied client-side."
          >
            <textarea
              id="aggrid-key"
              value={licenseKey}
              onChange={(e) => setLicenseKey(e.target.value)}
              rows={4}
              placeholder="Using_this_AG_Grid_Enterprise_key…"
              className="input font-mono text-xs"
              autoComplete="off"
            />
          </Field>
          <p className="mt-3 text-xs text-slate-500">
            Status: {data.licenseKeySet ? <Badge kind="ok">key set</Badge> : <Badge kind="warn">no key (watermarked)</Badge>}
          </p>
        </div>
        <button type="submit" className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save license key"}</button>
      </form>
    </section>
  );
}
