import { useEffect, useState } from "react";
import { useIsSuperuser } from "@modules/auth";
import { getVisibleAdminTabs, type AdminTab } from "../config/adminTabs";
import { postAdminUiActivity } from "../api/adminApi";
import { AdminActivityPanel } from "./AdminActivityPanel";
import { AdminContentPanel } from "./AdminContentPanel";
import { AdminDiagnosticsPanel } from "./AdminDiagnosticsPanel";
import { AdminShell } from "./AdminShell";
import { AdminSecurityPanel } from "./AdminSecurityPanel";
import { AdminUsersTable } from "./AdminUsersTable";

function AdminTabPanel({ tab, isSuperuser }: { tab: AdminTab; isSuperuser: boolean }): JSX.Element | null {
  switch (tab) {
    case "users":
      return <AdminUsersTable />;
    case "content":
      return <AdminContentPanel />;
    case "security":
      return isSuperuser ? <AdminSecurityPanel /> : null;
    case "diagnostics":
      return isSuperuser ? <AdminDiagnosticsPanel /> : null;
    case "activity":
      return <AdminActivityPanel />;
    default:
      return null;
  }
}

export function AdminPanel(): JSX.Element {
  const isSuperuser = useIsSuperuser();
  const [tab, setTab] = useState<AdminTab>("users");
  const visibleTabs = getVisibleAdminTabs(isSuperuser);

  useEffect(() => {
    if (!visibleTabs.some((item) => item.id === tab)) {
      setTab(visibleTabs[0]?.id ?? "users");
    }
  }, [isSuperuser, tab, visibleTabs]);

  return (
    <AdminShell
      tab={tab}
      isSuperuser={isSuperuser}
      onSelectTab={(nextTab) => {
        setTab(nextTab);
        void postAdminUiActivity("admin_tab_change", { tab: nextTab });
      }}
    >
      <div key={tab} className="wesp-admin-section-enter wesp-admin-block">
        <AdminTabPanel tab={tab} isSuperuser={isSuperuser} />
      </div>
    </AdminShell>
  );
}
