import { notFound } from "next/navigation";
import { DashboardPage } from "@/components/layout/dashboard-page";
import { withDashboardAccess } from "@/components/layout/dashboard-access";
import { FinancialReportLive } from "@/features/locations/financial-report-live";
import { PageHeader } from "@/components/shared/page";
import { loadFinancialReport } from "@/features/locations/financial-report-server";

const uuidPattern =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

function first(value: string | string[] | undefined): string | undefined {
  return Array.isArray(value) ? value[0] : value;
}

function defaultDateRange(): { startDate: string; endDate: string } {
  const endDate = new Date().toISOString().slice(0, 10);
  return { startDate: `${endDate.slice(0, 7)}-01`, endDate };
}

export default withDashboardAccess("/reports/financial-report", async function DashboardRoute(props: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}, role) {
  const query = await props.searchParams;
  const defaults = defaultDateRange();
  const startDate = first(query.start_date) || defaults.startDate;
  const endDate = first(query.end_date) || defaults.endDate;
  const locationId = first(query.location_id);
  if (locationId && !uuidPattern.test(locationId)) {
    notFound();
  }
  const { data, error } = await loadFinancialReport({
    startDate,
    endDate,
    locationId,
  });
  const locationName = data?.items.find(
    (item) => item.location_id === locationId,
  )?.location_name;
  const allLocationsQuery = new URLSearchParams({
    start_date: startDate,
    end_date: endDate,
  });
  return (
    <DashboardPage role={role}>
      {locationId && (
        <PageHeader
          title={locationName ?? "Location Financial Report"}
          parent={{
            label: "Financial Report",
            href: `/reports/financial-report?${allLocationsQuery.toString()}`,
          }}
        />
      )}
      <FinancialReportLive
        data={data ?? null}
        error={error ?? null}
        startDate={startDate}
        endDate={endDate}
        locationId={locationId}
        embedded={!!locationId}
        canExport={role === "admin"}
      />
    </DashboardPage>
  );
});
