"use client";

import { PageHeader, Tabs, type TabDef } from "@/components/ui";
import CredentialsPanel from "@/components/panels/CredentialsPanel";
import RuntimePanel from "@/components/panels/RuntimePanel";
import CostQualityPanel from "@/components/panels/CostQualityPanel";
import AuditPanel from "@/components/panels/AuditPanel";
import UsersRolesPanel from "@/components/panels/UsersRolesPanel";
import ActionsPanel from "@/components/panels/ActionsPanel";
import ServicesPanel from "@/components/panels/ServicesPanel";
import RunnersPanel from "@/components/panels/RunnersPanel";
import { useRoles } from "@/components/RolesProvider";
import { canControlRunners, canManageUsers, canSeeAdminConfig, canSeeCostControl } from "@/lib/roles";

export default function AdminSettingsPage() {
  const roles = useRoles();
  const admin = canSeeAdminConfig(roles); // superadmin + tech-admin

  const tabs: TabDef[] = [];
  // Integration + runtime config is admin-only.
  if (admin) {
    tabs.push({ id: "credentials", label: "Credentials", render: () => <CredentialsPanel /> });
    tabs.push({ id: "runtime", label: "Runtime", render: () => <RuntimePanel /> });
  }
  // Services is visible to everyone who can reach this page (admins and Service
  // Manager). Process-runner control stays admin-only within the tab.
  tabs.push({
    id: "services",
    label: "Services",
    render: () => (
      <>
        <ServicesPanel />
        {canControlRunners(roles) && <RunnersPanel />}
      </>
    ),
  });
  // User management is superadmin-only (it can grant roles and set passwords).
  if (canManageUsers(roles)) {
    tabs.push({ id: "users", label: "Users & Roles", render: () => <UsersRolesPanel /> });
  }
  // Cost control is superadmin-only (Tech-Admin is excluded).
  if (canSeeCostControl(roles)) {
    tabs.push({ id: "cost-quality", label: "Cost & Quality", render: () => <CostQualityPanel /> });
  }
  if (admin) {
    tabs.push({ id: "actions", label: "Actions", render: () => <ActionsPanel /> });
    tabs.push({ id: "audit", label: "Audit Log", render: () => <AuditPanel /> });
  }

  return (
    <>
      <PageHeader
        title="Admin Settings"
        description="Integration credentials, runtime tuning, and cost & quality controls — all admin-editable without a redeploy."
      />
      <Tabs tabs={tabs} />
    </>
  );
}
