import { useId } from "react";
import { PERMISSIONS } from "../../api/types";
import type { Permission } from "../../api/types";

/** Short human gloss for each permission so the checkbox list is self-explaining. */
const PERMISSION_LABEL: Record<Permission, string> = {
  view: "View sessions",
  control: "Take remote control",
  transfer: "Transfer files",
  manage_users: "Manage users",
  manage_clients: "Manage clients",
};

interface PermissionsFieldProps {
  /** Currently selected permission strings. */
  value: (Permission | string)[];
  onChange: (next: Permission[]) => void;
  /** Disable the whole group (e.g. while a save is in flight, or for admins). */
  disabled?: boolean;
  /**
   * When set, the group is read-only and shows this explanation instead of
   * being editable. Used for the `admin` role, whose permissions are implicit
   * (admins hold every permission server-side regardless of the stored set).
   */
  lockedNote?: string;
}

/**
 * Permission multiselect built from the REAL server permission catalog
 * (`PERMISSIONS`). The strings here are the exact ones the rest of the app
 * checks — no invented values. Renders as a labeled checkbox group.
 */
export function PermissionsField({
  value,
  onChange,
  disabled = false,
  lockedNote,
}: PermissionsFieldProps) {
  const groupId = useId();
  const selected = new Set(value);

  function toggle(perm: Permission, checked: boolean) {
    const next = new Set(selected);
    if (checked) next.add(perm);
    else next.delete(perm);
    // Preserve the canonical catalog order so the stored set is stable.
    onChange(PERMISSIONS.filter((p) => next.has(p)));
  }

  return (
    <fieldset className="permset" aria-describedby={lockedNote ? groupId : undefined}>
      <legend className="field__label">Permissions</legend>
      {lockedNote ? (
        <p className="permset__locked" id={groupId}>
          {lockedNote}
        </p>
      ) : (
        <div className="permset__grid">
          {PERMISSIONS.map((perm) => (
            <label key={perm} className="permset__opt">
              <input
                type="checkbox"
                checked={selected.has(perm)}
                disabled={disabled}
                onChange={(e) => toggle(perm, e.target.checked)}
              />
              <span className="permset__opttext">
                <span className="permset__optname">
                  {PERMISSION_LABEL[perm]}
                </span>
                <code className="permset__optcode mono">{perm}</code>
              </span>
            </label>
          ))}
        </div>
      )}
    </fieldset>
  );
}
