"use client";
import { useState } from "react";
import { Copy } from "lucide-react";
import { Badge, Button, Card, Field, Input, PageHeader, Select, Sheet, api, cx, useAction, useUI } from "@/components/ui";
import { useApi } from "@/components/hooks";

const LEVELS: Record<string, { label: string; tone: string }> = { C: { label: "C", tone: "green" }, V: { label: "V", tone: "blue" }, A: { label: "A", tone: "violet" }, "C:assigned": { label: "C (assigned)", tone: "amber" }, "V:own": { label: "V (own)", tone: "amber" }, "": { label: "—", tone: "gray" } };

export default function RolesPage() {
  const r = useApi<{ data: any[]; capabilities: { key: string; label: string }[] }>("/roles");
  const [edit, setEdit] = useState<any | "new" | null>(null);
  const { confirm, push } = useUI();
  const roles = r.data?.data ?? [];
  const caps = r.data?.capabilities ?? [];
  return (
    <>
      <PageHeader title="Roles & permissions" subtitle="C = create/edit · V = view · A = approve · enforced per workspace — default roles ship out of the box; clone one to customise"
        actions={<Button variant="primary" icon={<Copy className="h-3.5 w-3.5" />} onClick={() => setEdit("new")}>Clone a role</Button>} />
      <Card bodyClass="p-0">
        <div className="overflow-x-auto">
          <table className="table-mac min-w-[980px]">
            <thead><tr><th>Capability</th>{roles.map((x) => <th key={x.id} className="text-center">{x.name}{!x.isSystem && <div className="normal-case"><button className="text-brand" onClick={() => setEdit(x)}>edit</button> · <button className="text-bad" onClick={async () => { if (await confirm({ title: `Delete role “${x.name}”?`, danger: true, confirmLabel: "Delete" })) { try { await api(`/roles/${x.id}`, { method: "DELETE" }); r.reload(); } catch (e) { push("error", (e as Error).message); } } }}>delete</button></div>}</th>)}</tr></thead>
            <tbody>{caps.map((c) => (
              <tr key={c.key}><td className="font-medium">{c.label}</td>{roles.map((x) => { const l = LEVELS[x.permissions[c.key] ?? ""] ?? LEVELS[""]!; return <td key={x.id} className="text-center"><Badge tone={l.tone}>{l.label}</Badge></td>; })}</tr>
            ))}</tbody>
          </table>
        </div>
      </Card>
      {edit && <RoleSheet role={edit === "new" ? null : edit} roles={roles} caps={caps} onClose={() => setEdit(null)} onDone={() => { setEdit(null); r.reload(); }} />}
    </>
  );
}

function RoleSheet({ role, roles, caps, onClose, onDone }: { role: any | null; roles: any[]; caps: { key: string; label: string }[]; onClose: () => void; onDone: () => void }) {
  const [name, setName] = useState(role?.name ?? "");
  const [from, setFrom] = useState("marketing_manager");
  const base = role?.permissions ?? roles.find((x) => x.key === from)?.permissions ?? {};
  const [perms, setPerms] = useState<Record<string, string>>(role?.permissions ?? {});
  const eff = { ...base, ...perms };
  const { busy, run } = useAction();
  return (
    <Sheet open onClose={onClose} width={560} title={role ? `Edit ${role.name}` : "Clone a role"} footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { if (role) await api(`/roles/${role.id}`, { method: "PATCH", body: { name, permissions: eff } }); else await api("/roles", { body: { name, clone_from: from, permissions: perms } }); onDone(); }, "Role saved")}>Save</Button></>}>
      <div className="space-y-3">
        <div className="grid grid-cols-2 gap-3">
          <Field label="Role name"><Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Senior sales rep" /></Field>
          {!role && <Field label="Start from"><Select value={from} onChange={(e) => { setFrom(e.target.value); setPerms({}); }}>{roles.filter((x) => x.isSystem).map((x) => <option key={x.key} value={x.key}>{x.name}</option>)}</Select></Field>}
        </div>
        <div className="divide-y divide-line/60 rounded-[9px] border border-line">
          {caps.map((c) => (
            <div key={c.key} className="flex items-center justify-between gap-3 px-3 py-2">
              <span className="text-[13px]">{c.label}</span>
              <select className={cx("field w-[170px] py-1 text-[12.5px]", c.key === "agency" && "opacity-60")} disabled={c.key === "agency"} value={eff[c.key] ?? ""} onChange={(e) => setPerms({ ...perms, [c.key]: e.target.value })}>
                {Object.entries(LEVELS).map(([v, l]) => <option key={v} value={v}>{v === "" ? "None" : v === "C" ? "Create / edit" : v === "V" ? "View" : v === "A" ? "Approve" : l.label}</option>)}
              </select>
            </div>
          ))}
        </div>
        <p className="text-[11.5px] text-ink-3">Agency-level capabilities can only be granted by agency admins.</p>
      </div>
    </Sheet>
  );
}

