import React, { Suspense } from "react";
import { getShipments } from "@/actions/sales";
import { ShipmentsOverviewClient } from "./ShipmentsOverviewClient";
import { ShipmentsOverview } from "./columns";
import { DataTableSkeleton } from "@/components/dashboard/shared/DataTableSkeleton";

/**
 * ⚡ Optimization: Server-Side Rendering (SSR) for Shipments Overview
 * Moving data fetching to the server eliminates the client-side "useEffect" waterfall,
 * providing a faster initial load (FCP) and better UX by removing the "Laden..." flash.
 * Request deduplication is handled by React.cache in the server action.
 */
export default async function ShipmentsPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const params = await searchParams;
  const activePage = typeof params.page === "string" ? parseInt(params.page, 10) || 1 : 1;
  const pageSize = typeof params.pageSize === "string" ? parseInt(params.pageSize, 10) || 10 : 10;

  const response = await getShipments({ limit: pageSize, offset: (activePage - 1) * pageSize });

  // Prepare data for the client component
  const initialData = {
    documents: ("data" in response && response.data ? response.data.documents : []) as ShipmentsOverview[],
    total: "data" in response && response.data ? response.data.total : 0,
  };

  return (
    <Suspense key={`${activePage}-${pageSize}`} fallback={<DataTableSkeleton rowCount={Math.min(pageSize, 10)} />}>
      <ShipmentsOverviewClient
        initialData={initialData}
        activePage={activePage}
        pageSize={pageSize}
      />
    </Suspense>
  );
}
