import { loadScopedLocations } from "@/features/locations/location-server";
import { DashboardPage } from "@/components/layout/dashboard-page";
import { withDashboardAccess } from "@/components/layout/dashboard-access";
import { PageHeader } from "@/components/shared/page";
import { PayoutSettlements } from "@/features/analytics/financial/payout-settlements";
import { RoiPortfolio } from "@/features/analytics/financial/roi-portfolio";
import {
  loadFinancialChargepoints,
  loadFinancialInvestorGroups,
  loadFinancialInvestors,
  loadFinancialSection,
  loadInvestmentPortfolio,
} from "@/features/analytics/financial/server";
export default withDashboardAccess("/reports/roi", async function DashboardRoute({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}, role) {
  const query = await searchParams;
  const canEdit = role === "admin";
  const emptyOptions = { options: [], error: null };
  const page = (key: string) => {
    const value = Number(query[key] ?? 1);
    return Number.isSafeInteger(value) && value > 0 && value <= 10000
      ? value
      : 1;
  };
  const locationPortfolio = async () => {
    const aggregate = query.location_id === undefined ? loadInvestmentPortfolio() : null;
    const directory = await loadScopedLocations();
    const locations = directory.locations.map(({ id, name, currency }) => ({
      value: id,
      label: name,
      currency,
    }));
    const locationId =
      locations.find((location) => location.value === query.location_id)?.value ?? "";
    return {
      locations,
      locationError: directory.error,
      locationId,
      portfolio: await (aggregate ?? loadInvestmentPortfolio(locationId || undefined)),
    };
  };
  const [portfolio, groups, revenue, settlements, chargepoints, investors] = await Promise.all([
    locationPortfolio(),
    canEdit ? loadFinancialInvestorGroups() : emptyOptions,
    loadFinancialSection("revenue-shares", 1),
    loadFinancialSection("payout-settlements", page("settlement_page")),
    canEdit ? loadFinancialChargepoints() : emptyOptions,
    canEdit ? loadFinancialInvestors() : emptyOptions,
  ]);
  return (
    <DashboardPage role={role}>
      <PageHeader title="Return on Investment (ROI)" />
      <div className="min-w-0 space-y-6">
        <RoiPortfolio {...portfolio} groups={groups} canEdit={canEdit} />
        <PayoutSettlements
          canEdit={canEdit}
          chargepoints={chargepoints}
          investors={investors}
          revenue={revenue}
          settlements={settlements}
        />
      </div>
    </DashboardPage>
  );
});
