import { getOrdersByCustomerId } from "@/actions/orders";
import { DataTable } from "./data-table";
import PaginationWithLinks from "@/components/ui/pagination-with-links";
import { columns } from "./columns";
import { auth } from "@/auth";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { ShoppingBag } from "lucide-react";

export default async function CustomerOrdersPage({
  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 per_page =
    typeof params["pageSize"] === "string"
      ? parseInt(params["pageSize"], 10) || 5
      : 5;

  const session = await auth();

  const customerId = session?.user?.customer_id as string;

  const response = await getOrdersByCustomerId({
    customerId,
    limit: per_page,
    offset: (page - 1) * per_page
  });

  if (!response.success) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Fehler beim Laden der Bestellungen</CardTitle>
        </CardHeader>
        <CardContent>
          <p>{response.error}</p>
        </CardContent>
      </Card>
    );
  }

  const { documents, total } = response.data;

  return (
    <div className="flex flex-col gap-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <div className="flex flex-col gap-1.5">
        <h2 className="text-xl font-bold tracking-tight">Bestellungen</h2>
        <p className="text-sm text-muted-foreground">Hier findest du eine Liste all deiner bisherigen Bestellungen.</p>
      </div>

      {documents.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-center rounded-lg border border-dashed border-border/60 bg-muted/20">
          <div className="rounded-full bg-muted p-3 mb-4">
             <ShoppingBag className="w-6 h-6 text-muted-foreground" />
          </div>
          <h3 className="text-lg font-medium">Keine Bestellungen gefunden</h3>
          <p className="text-sm text-muted-foreground mt-1 max-w-xs">Es sieht so aus, als hättest du noch keine Bestellungen getätigt.</p>
        </div>
      ) : (
        <div className="space-y-6">
          <div className="rounded-md border border-border/40 overflow-hidden bg-card">
            <DataTable columns={columns} data={documents as any} />
          </div>
          <div className="flex items-center justify-end">
            <PaginationWithLinks
              page={page}
              pageSize={per_page}
              totalCount={total}
              pageSizeSelectOptions={{ pageSizeOptions: [5, 10, 20] }}
            />
          </div>
        </div>
      )}
    </div>
  );
}
