import { getUsers } from "@/actions/user";
import { UsersOverview } from "./columns";
import React, { Suspense } from "react";
import UsersOverviewClient from "./UsersOverviewClient";
import { ErrorDisplay } from "@/components/dashboard/shared/ErrorDisplay";
import { Button } from "@/components/ui/button";
import { UserPlus } from "lucide-react";
import Link from "next/link";

export default async function UsersPage({
  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 getUsers({ 
    limit: pageSize, 
    page: activePage,
    excludeRole: "customer" 
  });

  if (!response.success) {
    return (
      <div className="space-y-6">
        <div className="flex flex-col gap-2">
          <h1 className="text-2xl font-bold tracking-tight">Team-Verwaltung</h1>
          <p className="text-muted-foreground">Verwalten Sie die Benutzerkonten Ihres Teams.</p>
        </div>
        <ErrorDisplay title="Ladefehler" error={response.error} />
      </div>
    );
  }

  const initialData = response.data;

  return (
    <Suspense
      key={`${activePage}-${pageSize}`}
      fallback={<div className="h-96 flex items-center justify-center text-muted-foreground">Laden...</div>}
    >
      <UsersOverviewClient
        initialData={initialData as { documents: UsersOverview[]; total: number }}
        activePage={activePage}
        pageSize={pageSize}
      />
    </Suspense>
  );
}
