"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Icon } from "@/components/ui/Icon";
import { confirmDialog, alertDialog } from "@/components/ui/Dialog";
import { createRoleAction, updateRoleAction, deleteRoleAction } from "@/lib/admin/actions";
import type { AdminRole, PermissionGroup } from "@/lib/admin/queries";

export function RolesManager({
  roles,
  groups,
}: {
  roles: AdminRole[];
  groups: PermissionGroup[];
}) {
  const router = useRouter();
  const [editing, setEditing] = useState<AdminRole | "new" | null>(null);

  const onDelete = async (r: AdminRole) => {
    if (
      !(await confirmDialog({
        title: "Rolle löschen?",
        message:
          r.userCount > 0
            ? `„${r.name}" ist ${r.userCount} Nutzer(n) zugewiesen. Die Zuweisung wird entfernt.`
            : `„${r.name}" wird entfernt.`,
        danger: true,
      }))
    )
      return;
    const res = await deleteRoleAction(r.id);
    if (res.error) await alertDialog({ title: "Nicht möglich", message: res.error, danger: true });
    else router.refresh();
  };

  return (
    <>
      <section className="card" data-reveal>
        <div className="mb-4 flex items-center justify-between">
          <div>
            <h2>Rollen &amp; Rechte</h2>
            <p className="text-muted text-xs mt-0.5">
              Änderungen greifen für Nutzer nach dem nächsten Login.
            </p>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => setEditing("new")}>
            <Icon name="plus" size={15} /> Rolle erstellen
          </button>
        </div>

        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
          {roles.map((r) => (
            <div key={r.id} className="card-sm" style={{ background: "rgba(13,19,42,.4)" }}>
              <div className="flex items-center justify-between gap-2">
                <h3 className="truncate">{r.name}</h3>
                {r.isSystem ? <span className="badge">System</span> : null}
              </div>
              <p className="text-muted mt-1 text-sm min-h-[2.5em]">{r.description}</p>
              <div className="mt-3 flex flex-wrap items-center gap-2">
                <span className="badge">{r.permissionKeys.length} Rechte</span>
                <span className="badge">{r.userCount} Nutzer</span>
              </div>
              <div className="mt-3 flex items-center gap-2">
                <button className="btn btn-ghost btn-sm" onClick={() => setEditing(r)}>
                  <Icon name="edit" size={14} /> Bearbeiten
                </button>
                {r.key !== "ADMIN" ? (
                  <button className="btn btn-ghost btn-sm" onClick={() => onDelete(r)} title="Rolle löschen">
                    <Icon name="trash" size={14} /> Löschen
                  </button>
                ) : null}
              </div>
            </div>
          ))}
        </div>
      </section>

      {editing ? (
        <RoleDrawer
          role={editing === "new" ? null : editing}
          groups={groups}
          onClose={() => setEditing(null)}
        />
      ) : null}
    </>
  );
}

function RoleDrawer({
  role,
  groups,
  onClose,
}: {
  role: AdminRole | null;
  groups: PermissionGroup[];
  onClose: () => void;
}) {
  const router = useRouter();
  const isNew = !role;
  const isAdmin = role?.key === "ADMIN";
  const [name, setName] = useState(role?.name ?? "");
  const [description, setDescription] = useState(role?.description ?? "");
  const [keys, setKeys] = useState<string[]>(role?.permissionKeys ?? []);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const has = (k: string) => keys.includes(k);
  const toggle = (k: string) => setKeys((s) => (s.includes(k) ? s.filter((x) => x !== k) : [...s, k]));
  const toggleGroup = (g: PermissionGroup) => {
    const all = g.items.every((i) => has(i.key));
    setKeys((s) => {
      const set = new Set(s);
      g.items.forEach((i) => (all ? set.delete(i.key) : set.add(i.key)));
      return [...set];
    });
  };

  const save = async () => {
    setSaving(true);
    setError(null);
    const res = isNew
      ? await createRoleAction({ name, description, permissionKeys: keys })
      : await updateRoleAction(role!.id, { name, description, permissionKeys: keys });
    setSaving(false);
    if (res.error) return setError(res.error);
    onClose();
    router.refresh();
  };

  return (
    <div className="drawer-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="drawer animate-in">
        <div className="mb-5 flex items-center justify-between">
          <span className="eyebrow">{isNew ? "Neue Rolle" : "Rolle bearbeiten"}</span>
          <button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="Schließen">
            <Icon name="close" size={16} />
          </button>
        </div>

        {error ? <p className="field-error mb-3">{error}</p> : null}

        <div className="flex flex-col gap-4">
          <div className="field">
            <label className="label">Name</label>
            <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="z. B. Redaktion" />
          </div>
          <div className="field">
            <label className="label">Beschreibung</label>
            <input className="input" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Kurzbeschreibung" />
          </div>

          <div className="field">
            <label className="label">Berechtigungen</label>
            {isAdmin ? (
              <p className="text-muted text-sm">Die Admin-Rolle besitzt dauerhaft alle Rechte.</p>
            ) : (
              <div className="flex flex-col gap-3">
                {groups.map((g) => {
                  const all = g.items.every((i) => has(i.key));
                  return (
                    <div key={g.module} className="perm-group">
                      <button type="button" className="perm-group-head" onClick={() => toggleGroup(g)}>
                        <span className="font-bold">{g.moduleLabel}</span>
                        <span className="badge">{all ? "Alle" : `${g.items.filter((i) => has(i.key)).length}/${g.items.length}`}</span>
                      </button>
                      <div className="flex flex-col gap-1 p-2">
                        {g.items.map((i) => (
                          <button key={i.key} type="button" className="perm-item" data-active={has(i.key)} onClick={() => toggle(i.key)}>
                            <span className="perm-check" data-active={has(i.key)}>
                              {has(i.key) ? <Icon name="check" size={12} /> : null}
                            </span>
                            <span className="min-w-0 flex-1">{i.description}</span>
                            <code className="text-muted text-xs">{i.key}</code>
                          </button>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

        </div>

        <div className="form-footer">
          <span />
          <div className="flex items-center gap-2">
            <button className="btn btn-ghost" onClick={onClose} disabled={saving}>Abbrechen</button>
            <button className="btn btn-primary" onClick={save} disabled={saving || !name.trim()}>
              {saving ? "Speichern …" : isNew ? "Erstellen" : "Speichern"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
