import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { getCtx } from "@/lib/ctx";

type Row = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any

const s = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();

// Khusus super admin (kamu): membuat perusahaan baru beserta akun owner-nya
async function createOrg(fd: FormData) {
  "use server";
  const c = await getCtx();
  if (!c.isSuper) redirect("/");

  const name = s(fd, "name");
  const slug = s(fd, "slug").toLowerCase();
  const email = s(fd, "email").toLowerCase();
  const password = s(fd, "password");
  if (!name || !/^[a-z0-9-]{3,40}$/.test(slug) || !email || password.length < 8) redirect("/admin?e=Data+belum+lengkap");

  const { data: org, error } = await c.admin.from("organizations").insert({ name, slug }).select("id").single();
  if (error || !org) redirect(`/admin?e=${encodeURIComponent(error?.message ?? "Gagal membuat perusahaan")}`);

  const { data: u, error: ue } = await c.admin.auth.admin.createUser({
    email,
    password,
    email_confirm: true,
    user_metadata: { full_name: s(fd, "owner_name") || email },
  });
  if (ue || !u.user) {
    await c.admin.from("organizations").delete().eq("id", org!.id);
    redirect(`/admin?e=${encodeURIComponent(ue?.message ?? "Gagal membuat user owner")}`);
  }
  await c.admin.from("memberships").insert({ org_id: org!.id, user_id: u.user!.id, role: "owner" });
  await c.admin.from("meta_connections").insert({ org_id: org!.id, dataset_id: "" });
  revalidatePath("/admin");
  redirect("/admin");
}

async function toggleOrg(fd: FormData) {
  "use server";
  const c = await getCtx();
  if (!c.isSuper) redirect("/");
  await c.admin.from("organizations").update({ is_active: s(fd, "active") === "1" }).eq("id", s(fd, "id"));
  revalidatePath("/admin");
}

export default async function Admin({ searchParams }: { searchParams: Promise<{ e?: string }> }) {
  const { e } = await searchParams;
  const c = await getCtx();
  if (!c.isSuper) redirect("/");
  const { data } = await c.admin.from("organizations").select("id, name, slug, plan, is_active, created_at").order("created_at", { ascending: false });
  const orgs: Row[] = data ?? [];

  return (
    <>
      <h1>Admin platform</h1>
      {e && <div className="alert">{e}</div>}
      <div className="card">
        <h2>Perusahaan baru</h2>
        <form action={createOrg}>
          <div className="row fill">
            <input name="name" placeholder="Nama perusahaan" required />
            <input name="slug" placeholder="slug-perusahaan" required />
          </div>
          <div className="row fill">
            <input name="owner_name" placeholder="Nama owner" />
            <input name="email" type="email" placeholder="Email owner" required />
            <input name="password" type="text" placeholder="Password awal (min. 8)" required />
          </div>
          <p><button className="btn">Buat perusahaan &amp; owner</button></p>
        </form>
      </div>
      <div className="card scroll">
        <table>
          <thead><tr><th>Perusahaan</th><th>Slug</th><th>Paket</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {orgs.map((o) => (
              <tr key={o.id}>
                <td>{o.name}</td><td className="muted">{o.slug}</td><td>{o.plan}</td>
                <td className={o.is_active ? "ok" : "hot"}>{o.is_active ? "aktif" : "nonaktif"}</td>
                <td>
                  <form action={toggleOrg}>
                    <input type="hidden" name="id" value={o.id} />
                    <input type="hidden" name="active" value={o.is_active ? "0" : "1"} />
                    <button className="btn ghost">{o.is_active ? "Nonaktifkan" : "Aktifkan"}</button>
                  </form>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}
