import { PageHeader } from "@/components/shared/page-header";
import { getCustomers } from "@/features/customers/api";
import { CustomerView } from "@/features/customers/customer-view";
import type { CustomerApiPage } from "@/features/customers/api-contract";
import { readCustomerListQuery } from "@/features/customers/customer-query";
import type { CustomerRecord } from "@/features/customers/types";
import type { SearchParams } from "@/lib/list-query";
import { getServerSession } from "@/lib/auth/server-session";

export const metadata = { title: "Customers (EV Driver)" };

export default async function CustomersPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const session = await getServerSession();
  const query = readCustomerListQuery(await searchParams);
  let customers: CustomerRecord[] = [];
  let pagination: CustomerApiPage["pagination"] = {
    totalDocs: 0,
    limit: query.limit,
    totalPages: 0,
    page: query.page,
    pagingCounter: 0,
    hasPrevPage: query.page > 1,
    hasNextPage: false,
    prevPage: query.page > 1 ? query.page - 1 : 0,
    nextPage: 0,
  };
  let loadError: string | undefined;
  try {
    const result = await getCustomers(query);
    customers = result.customers;
    pagination = result.pagination;
  } catch (error) {
    loadError = error instanceof Error
      ? error.message
      : "Unable to load customers. Refresh and try again.";
  }

  return (
    <>
      <PageHeader title="Customers" />
      <CustomerView
        initialCustomers={customers}
        pagination={pagination}
        query={query}
        canManage={session?.role === "admin"}
        loadError={loadError}
      />
    </>
  );
}
