"use client";

import { Fragment, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { useAuth } from "@/hooks/useAuth";
import { Check, Lock, Save } from "lucide-react";

interface PermissionDef {
  key: string;
  label: string;
  group: string;
}

type Matrix = Record<string, Record<string, boolean>>;

const ROLE_LABELS: Record<string, string> = {
  admin: "Admin",
  moderator: "Moderator",
  writer: "Writer",
};

function buildMatrix(
  roles: string[],
  perms: PermissionDef[],
  granted: Record<string, string[]>
): Matrix {
  const matrix: Matrix = {};
  for (const role of roles) {
    matrix[role] = {};
    const set = new Set(granted[role] ?? []);
    for (const perm of perms) {
      matrix[role][perm.key] = set.has(perm.key);
    }
  }
  return matrix;
}

export default function RolesPage() {
  const { can } = useAuth();
  const allowed = can("roles.edit_permissions");

  const [permissions, setPermissions] = useState<PermissionDef[]>([]);
  const [roles, setRoles] = useState<string[]>([]);
  const [matrix, setMatrix] = useState<Matrix>({});
  const [original, setOriginal] = useState<Matrix>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [savingRole, setSavingRole] = useState<string | null>(null);
  const [notice, setNotice] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const [registry, current] = await Promise.all([
        api.getPermissionRegistry(),
        api.getRolePermissions(),
      ]);
      const granted: Record<string, string[]> = {};
      for (const r of current.roles) granted[r.role] = r.permissions;
      const built = buildMatrix(registry.roles, registry.permissions, granted);
      setPermissions(registry.permissions);
      setRoles(registry.roles);
      setMatrix(built);
      setOriginal(built);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (allowed) load();
    else setLoading(false);
  }, [allowed]);

  const groups = useMemo(() => {
    const order: string[] = [];
    const byGroup: Record<string, PermissionDef[]> = {};
    for (const perm of permissions) {
      if (!byGroup[perm.group]) {
        byGroup[perm.group] = [];
        order.push(perm.group);
      }
      byGroup[perm.group].push(perm);
    }
    return order.map((group) => ({ group, perms: byGroup[group] }));
  }, [permissions]);

  const dirtyRoles = useMemo(() => {
    return roles.filter((role) =>
      permissions.some((perm) => matrix[role]?.[perm.key] !== original[role]?.[perm.key])
    );
  }, [roles, permissions, matrix, original]);

  const toggle = (role: string, key: string) => {
    setNotice("");
    setMatrix((prev) => ({
      ...prev,
      [role]: { ...prev[role], [key]: !prev[role]?.[key] },
    }));
  };

  const saveRole = async (role: string) => {
    setSavingRole(role);
    setError("");
    setNotice("");
    try {
      const keys = permissions.filter((p) => matrix[role]?.[p.key]).map((p) => p.key);
      await api.updateRolePermissions(role, keys);
      setOriginal((prev) => ({ ...prev, [role]: { ...matrix[role] } }));
      setNotice(`${ROLE_LABELS[role] ?? role} permissions saved.`);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSavingRole(null);
    }
  };

  if (!allowed) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">
          You do not have permission to manage roles.
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading roles...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-on-surface">Roles and Permissions</h1>
        <p className="text-on-surface/60 text-sm mt-1">
          Toggle what each role can do. SuperAdmin always has every permission and
          cannot be changed.
        </p>
      </div>

      {error && <p className="text-error text-sm">{error}</p>}
      {notice && <p className="text-primary text-sm">{notice}</p>}

      <div className="bg-surface-container-low rounded-xl overflow-x-auto">
        <table className="w-full text-sm border-collapse">
          <thead>
            <tr className="text-left">
              <th className="sticky left-0 bg-surface-container-low p-4 font-semibold text-on-surface/70">
                Permission
              </th>
              {roles.map((role) => (
                <th key={role} className="p-4 text-center font-semibold text-on-surface/70">
                  {ROLE_LABELS[role] ?? role}
                </th>
              ))}
              <th className="p-4 text-center font-semibold text-on-surface/70">
                <span className="inline-flex items-center gap-1">
                  <Lock size={12} />
                  SuperAdmin
                </span>
              </th>
            </tr>
          </thead>
          <tbody>
            {groups.map(({ group, perms }) => (
              <Fragment key={group}>
                <tr>
                  <td
                    colSpan={roles.length + 2}
                    className="bg-surface-container px-4 py-2 text-xs font-bold uppercase tracking-wide text-on-surface/50"
                  >
                    {group}
                  </td>
                </tr>
                {perms.map((perm) => (
                  <tr key={perm.key} className="border-b border-surface-container-high/40">
                    <td className="sticky left-0 bg-surface-container-low p-4">
                      <div className="text-on-surface">{perm.label}</div>
                      <div className="text-on-surface/40 text-xs font-mono">{perm.key}</div>
                    </td>
                    {roles.map((role) => (
                      <td key={role} className="p-4 text-center">
                        <input
                          type="checkbox"
                          checked={!!matrix[role]?.[perm.key]}
                          onChange={() => toggle(role, perm.key)}
                          className="h-4 w-4 accent-primary cursor-pointer"
                          aria-label={`${ROLE_LABELS[role] ?? role}: ${perm.label}`}
                        />
                      </td>
                    ))}
                    <td className="p-4 text-center text-primary/70">
                      <Check size={16} className="inline" aria-label="Always granted" />
                    </td>
                  </tr>
                ))}
              </Fragment>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex flex-wrap gap-3">
        {roles.map((role) => {
          const dirty = dirtyRoles.includes(role);
          return (
            <button
              key={role}
              onClick={() => saveRole(role)}
              disabled={!dirty || savingRole === role}
              className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              <Save size={16} />
              {savingRole === role
                ? "Saving..."
                : `Save ${ROLE_LABELS[role] ?? role}${dirty ? " *" : ""}`}
            </button>
          );
        })}
      </div>
    </div>
  );
}
