import { verifySession } from "@/lib/auth";
import { pgGetCustomers, pgGetCustomerCategories, pgGetSalesReps } from "@/lib/postgres/data-access";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import ListManager from "@/components/admin/list-manager";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Info } from "lucide-react";
import type { Customer, CustomerCategory, SalesRep } from "@/lib/types";

export default async function ManageCustomersPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global ?? {};
  const tLists = t.ItemLists ?? {};
  const currencySymbol = await getCurrencySymbolAsync();

  if (!user || user.role !== 'admin') {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? "Access Denied"}</h1>
        <p>{tGlobal?.noPermission ?? "You do not have permission to view this page."}</p>
      </div>
    );
  }

  const customers: Customer[] = (await pgGetCustomers({ page: 1, pageSize: 5000 })).items as Customer[];
  const categories: CustomerCategory[] = (await pgGetCustomerCategories({ page: 1, pageSize: 5000 })).items as CustomerCategory[];
  const salesReps: SalesRep[] = (await pgGetSalesReps({ page: 1, pageSize: 5000 })).items as SalesRep[];

  return (
    <div className="space-y-4">
        <Alert>
            <Info className="h-4 w-4" />
            <AlertTitle>{tLists.customerInfoTitle ?? "ملاحظة"}</AlertTitle>
            <AlertDescription>{tLists.customerInfoDescription ?? "يمكن تعديل أسماء العملاء من هنا. تتم إضافة العملاء الجدد وأرصدتهم من خلال صفحة تقرير الإنتاج."}</AlertDescription>
        </Alert>
        <ListManager
            items={customers}
            title={tLists?.manageCustomers ?? "إدارة العملاء"}
            description={tLists?.manageCustomersDescription ?? "تعديل وحذف العملاء الحاليين."}
            itemType="customer"
            categories={categories}
          salesReps={salesReps}
            t={tLists}
            tGlobal={tGlobal}
            currencySymbol={currencySymbol}
        />
    </div>
  );
}
