import { lazy } from "react";
import {
  ModuleSubnav,
  hasAnyScope,
  useGuardedNavigate,
  type ApiSettings,
  type AuthInfo,
  type ModuleSubnavGroup
} from "@govoplan/core-webui";
import { OPERATOR_QUEUE_ROUTE_SCOPES } from "../operator/operatorQueueAccess";

const CampaignListPage = lazy(() => import("./CampaignListPage"));
const OperatorQueuePage = lazy(() => import("../operator/OperatorQueuePage"));
const AggregateReportsPage = lazy(() => import("../reports/AggregateReportsPage"));

export type CampaignModuleSection = "campaigns" | "queue" | "reports";

export default function CampaignModulePage({
  active,
  settings,
  auth
}: {
  active: CampaignModuleSection;
  settings: ApiSettings;
  auth: AuthInfo;
}) {
  const navigate = useGuardedNavigate();
  const canReadCampaigns = hasAnyScope(auth, ["campaigns:campaign:read"]);
  const canUseQueue =
    canReadCampaigns && hasAnyScope(auth, OPERATOR_QUEUE_ROUTE_SCOPES);
  const canReadReports = hasAnyScope(auth, ["campaigns:report:read"]);
  const groups: ModuleSubnavGroup<CampaignModuleSection>[] = [{
    items: [
      ...(canReadCampaigns
        ? [{
            id: "campaigns" as const,
            label: "i18n:govoplan-campaign.all_campaigns.2bd1ee3a",
            primary: true
          }]
        : []),
      ...(canUseQueue
        ? [{
            id: "queue" as const,
            label: "i18n:govoplan-campaign.operator_queue.72492fb5"
          }]
        : []),
      ...(canReadReports
        ? [{
            id: "reports" as const,
            label: "i18n:govoplan-campaign.reports.88bc3fe3",
            primary: !canReadCampaigns
          }]
        : [])
    ]
  }];

  function select(section: CampaignModuleSection) {
    const routes: Record<CampaignModuleSection, string> = {
      campaigns: "/campaigns",
      queue: "/campaigns/queue",
      reports: "/campaigns/reports"
    };
    navigate(routes[section]);
  }

  return (
    <div className="workspace campaign-module-workspace">
      <ModuleSubnav active={active} groups={groups} onSelect={select} />
      <section className="workspace-content">
        {active === "queue"
          ? <OperatorQueuePage settings={settings} auth={auth} />
          : active === "reports"
            ? <AggregateReportsPage settings={settings} />
            : <CampaignListPage settings={settings} />}
      </section>
    </div>
  );
}
