"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { updatePositionPermissionsAction, deletePositionAction, updatePositionNameAction, updatePositionSalaryAction } from "@/lib/actions/team";
import { PERMISSIONS, PERMISSION_AREA_GROUPS, type Permission } from "@/lib/permissions";
import { RenameField } from "@/components/admin/RenameField";
import { HourlyWageField } from "@/components/admin/HourlyWageField";

const ACTION_COLUMN_LABELS: Record<"view" | "create" | "edit" | "delete", string> = {
  view: "Ansehen",
  create: "Erstellen",
  edit: "Bearbeiten",
  delete: "Löschen",
};
const ALL_ACTIONS: ("view" | "create" | "edit" | "delete")[] = ["view", "create", "edit", "delete"];

function permissionKey(area: string, action: string, isSingle: boolean): Permission {
  return (isSingle ? area : `${area}_${action}`) as Permission;
}

export function PositionRow({
  position,
  departmentName,
}: {
  position: { id: string; name: string; permissions: Permission[] | null; defaultHourlyWage: number | null };
  departmentName: string;
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  // Bewusst lokaler React-State statt eines unkontrollierten Formulars mit
  // "bei jeder Änderung sofort speichern" — sonst würde das Abhaken von
  // "Vollzugriff" das Formular abschicken, BEVOR die Detail-Tabelle
  // überhaupt im DOM erscheint, und dabei versehentlich alle Rechte auf
  // einen Schlag löschen (genau dieser Bug ist hier schon einmal passiert).
  const initialFullAccess = position.permissions === null;
  const [fullAccess, setFullAccess] = useState(initialFullAccess);
  const [granted, setGranted] = useState<Set<Permission>>(new Set(position.permissions ?? PERMISSIONS));
  const [dirty, setDirty] = useState(false);
  const [saved, setSaved] = useState(false);

  const singleAreas = PERMISSION_AREA_GROUPS.filter((g) => g.actions.length === 1);
  const matrixAreas = PERMISSION_AREA_GROUPS.filter((g) => g.actions.length > 1);

  function toggleFullAccess(next: boolean) {
    setFullAccess(next);
    // Beim erstmaligen Wechsel von Vollzugriff zur Detailansicht: alle
    // Häkchen als Ausgangspunkt gesetzt lassen (entspricht dem bisherigen
    // Zustand), damit nichts unbeabsichtigt wegfällt — der Admin schränkt
    // dann gezielt ein, statt bei null anzufangen.
    if (!next && granted.size === 0) setGranted(new Set(PERMISSIONS));
    setDirty(true);
    setSaved(false);
  }

  function togglePermission(key: Permission) {
    setGranted((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
    setDirty(true);
    setSaved(false);
  }

  function save() {
    const data = new FormData();
    if (fullAccess) data.set("fullAccess", "on");
    else {
      for (const p of granted) data.set(`perm_${p}`, "on");
    }
    startTransition(async () => {
      await updatePositionPermissionsAction(position.id, data);
      setDirty(false);
      setSaved(true);
      router.refresh();
    });
  }

  return (
    <div className="bg-[var(--rk-surface)] border border-white/10 rounded-xl px-4 py-3">
      <div className="flex items-center justify-between gap-3 mb-2">
        <span className="flex items-center gap-1.5 text-sm">
          <RenameField id={position.id} name={position.name} action={updatePositionNameAction} />
          <span className="text-xs text-[var(--rk-ink-muted)]">· {departmentName || "—"}</span>
        </span>
        <div className="flex items-center gap-3">
          <HourlyWageField id={position.id} value={position.defaultHourlyWage} fieldName="defaultHourlyWage" action={updatePositionSalaryAction} />
        <button
          disabled={pending}
          onClick={() => {
            if (confirm(`Position „${position.name}" wirklich löschen?`)) {
              startTransition(async () => {
                await deletePositionAction(position.id);
                router.refresh();
              });
            }
          }}
          className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50 shrink-0"
        >
          Löschen
        </button>
        </div>
      </div>

      <label className="flex items-center gap-2 text-xs mb-3">
        <input
          type="checkbox"
          checked={fullAccess}
          disabled={pending}
          onChange={(e) => toggleFullAccess(e.target.checked)}
          className="h-3.5 w-3.5"
        />
        Vollzugriff (alle Bereiche, alle Aktionen)
      </label>

      {!fullAccess && (
        <>
          <div className="overflow-x-auto mb-4">
            <table className="text-xs border-collapse w-full">
              <thead>
                <tr className="text-[var(--rk-ink-muted)]">
                  <th className="text-left font-normal pb-1.5 pr-3">Bereich</th>
                  {ALL_ACTIONS.map((a) => (
                    <th key={a} className="text-center font-normal pb-1.5 px-2">
                      {ACTION_COLUMN_LABELS[a]}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {matrixAreas.map((group) => (
                  <tr key={group.area} className="border-t border-white/5">
                    <td className="py-1.5 pr-3 whitespace-nowrap">{group.label}</td>
                    {ALL_ACTIONS.map((action) =>
                      group.actions.includes(action) ? (
                        <td key={action} className="text-center py-1.5 px-2">
                          <input
                            type="checkbox"
                            checked={granted.has(permissionKey(group.area, action, false))}
                            disabled={pending}
                            onChange={() => togglePermission(permissionKey(group.area, action, false))}
                            className="h-3.5 w-3.5"
                          />
                        </td>
                      ) : (
                        <td key={action} className="text-center py-1.5 px-2 text-[var(--rk-ink-muted)]/30">
                          —
                        </td>
                      )
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <p className="text-[0.6rem] uppercase tracking-[0.08em] text-[var(--rk-ink-muted)] mb-1.5">Weitere Berechtigungen</p>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-x-3 gap-y-1.5 mb-4">
            {singleAreas.map((group) => (
              <label key={group.area} className="flex items-center gap-1.5 text-xs">
                <input
                  type="checkbox"
                  checked={granted.has(permissionKey(group.area, "view", true))}
                  disabled={pending}
                  onChange={() => togglePermission(permissionKey(group.area, "view", true))}
                  className="h-3.5 w-3.5"
                />
                {group.label}
              </label>
            ))}
          </div>
        </>
      )}

      <div className="flex items-center gap-3">
        <button
          type="button"
          disabled={pending || !dirty}
          onClick={save}
          className="text-xs border border-white/30 rounded-lg px-3.5 py-1.5 hover:border-white disabled:opacity-40 transition-colors"
        >
          Speichern
        </button>
        {saved && !dirty && <span className="text-xs text-emerald-400">Gespeichert.</span>}
        {dirty && <span className="text-xs text-amber-400">Ungespeicherte Änderungen.</span>}
      </div>
    </div>
  );
}
