import React, { Suspense } from "react";
import { getSuppliers } from "@/actions/settings";
import SuppliersOverviewClient from "./SuppliersOverviewClient";
import { SuppliersOverview } from "./columns";
import { ErrorDisplay } from "@/components/dashboard/shared/ErrorDisplay";

/**
 * ⚡ Optimization: Server-Side Rendering (SSR) for Suppliers
 * - Fetching data on the server eliminates the client-side fetch waterfall.
 * - Improves TTFB and FCP by providing initial data in the HTML.
 * - Leverages React.cache for deduplicated data fetching.
 */
export default async function SuppliersPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const params = await searchParams;
  const page =
    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 getSuppliers({ limit: pageSize, page });

  if (!response.success) {
    return (
      <div className="space-y-6">
        <div className="flex flex-col gap-2">
          <h1 className="text-2xl font-bold tracking-tight">Lieferanten</h1>
          <p className="text-muted-foreground">Fehler beim Laden der Lieferantendaten.</p>
        </div>
        <ErrorDisplay 
          title="Ladefehler" 
          error={response.error} 
        />
      </div>
    );
  }

  const { documents, pagination } = response.data;
  const total = pagination.total;

  return (
    <Suspense
      key={`${page}-${pageSize}`}
      fallback={
        <div className="p-10 text-center text-muted-foreground">Laden...</div>
      }
    >
      <SuppliersOverviewClient
        initialData={{
          documents: documents as SuppliersOverview[],
          total: total,
        }}
        page={page}
        pageSize={pageSize}
      />
    </Suspense>
  );
}
