import { useMemo, useState } from "react";
import OmsorgCard from "../../components/OmsorgCard";
import RolesPanel from "./RolesPanel";
import UserOverridesPanel from "./UserOverridesPanel";
import StatusManagementPanel from "./StatusManagementPanel";
import AssignmentValidationSettingsPanel from "./AssignmentValidationSettingsPanel";
import UsersPanel from "./UsersPanel";
import { useAuth } from "../../app/AuthContext";

const ALL_TABS = [
  { id: "users", label: "Benutzer", module: "Users" },
  { id: "roles", label: "Rollen", module: "UserManagement" },
  { id: "overrides", label: "Benutzerrechte", module: "UserManagement" },
  { id: "statuses", label: "Status-Verwaltung", module: "Configuration" },
  { id: "assignmentValidation", label: "Zuweisungsprüfung", module: "Configuration" },
];

export default function SettingsPage() {
  const { hasPermission } = useAuth();
  const tabs = useMemo(() => ALL_TABS.filter((tab) => hasPermission(tab.module, "View")), [hasPermission]);
  const [activeTab, setActiveTab] = useState(tabs[0]?.id ?? null);
  const currentTab = tabs.find((tab) => tab.id === activeTab) ? activeTab : tabs[0]?.id ?? null;

  return (
    <OmsorgCard title="Einstellungen">
      {tabs.length === 0 && <p>Keine Berechtigung für diesen Bereich.</p>}

      {tabs.length > 0 && (
        <>
          <div className="settings-tabs">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                type="button"
                className={tab.id === currentTab ? "settings-tab settings-tab--active" : "settings-tab"}
                onClick={() => setActiveTab(tab.id)}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {currentTab === "users" && <UsersPanel />}
          {currentTab === "roles" && <RolesPanel />}
          {currentTab === "overrides" && <UserOverridesPanel />}
          {currentTab === "statuses" && <StatusManagementPanel />}
          {currentTab === "assignmentValidation" && <AssignmentValidationSettingsPanel />}
        </>
      )}
    </OmsorgCard>
  );
}
