import { getTranslations, getCurrentLocale } from "@/lib/i18n";

import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { formatCurrency as formatCurrencyUtil } from "@/lib/currency-formatter";

export default async function SupplierBalancesPage() {
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tPurchases = t.Purchases ?? {};

  const suppliers = (await (await import('@/lib/postgres/data-access')).pgGetSuppliers({ page: 1, pageSize: 5000 })).items;
  const totalBalance = (suppliers as Array<Record<string, unknown>>).reduce(
    (sum, supplier) => sum + Number(supplier.balance || 0),
    0
  );
  const currencySymbol = await getCurrencySymbolAsync();
  const formatAmount = (amount: number) => formatCurrencyUtil(amount, currencySymbol);

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>{tPurchases.supplierBalances ?? 'أرصدة الموردين'}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-2 rounded-md border p-4">
              <div className="text-sm text-muted-foreground">{tPurchases.totalSuppliers ?? 'إجمالي الموردين'}</div>
              <div className="text-2xl font-bold">{suppliers.length}</div>
            </div>
            <div className="space-y-2 rounded-md border p-4">
              <div className="text-sm text-muted-foreground">{tPurchases.totalBalance ?? 'إجمالي الأرصدة'}</div>
              <div className="text-2xl font-bold">{formatAmount(totalBalance)}</div>
            </div>
            <div className="space-y-2 rounded-md border p-4">
              <div className="text-sm text-muted-foreground">{tPurchases.averageBalance ?? 'متوسط الرصيد'}</div>
              <div className="text-2xl font-bold">
                {suppliers.length > 0 ? formatAmount(totalBalance / suppliers.length) : formatAmount(0)}
              </div>
            </div>
          </div>

          <div className="rounded-md border">
            <div className="relative w-full overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{tPurchases.supplierName ?? 'اسم المورد'}</TableHead>
                    <TableHead>{tPurchases.supplierNumber ?? 'رقم المورد'}</TableHead>
                    <TableHead>{tPurchases.phone ?? 'الهاتف'}</TableHead>
                    <TableHead>{tPurchases.paymentTerms ?? 'شروط الدفع'}</TableHead>
                    <TableHead className="text-right">{tPurchases.balance ?? 'الرصيد'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {suppliers.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center text-muted-foreground py-8">
                        {tPurchases.noSuppliers ?? 'لا توجد موردين'}
                      </TableCell>
                    </TableRow>
                  ) : (
                    (suppliers as Array<Record<string, unknown>>).map((supplier) => {
                      const balance = Number(supplier.balance || 0);
                      return (
                      <TableRow key={String(supplier.id || '')}>
                        <TableCell className="font-medium">{String(supplier.name || '')}</TableCell>
                        <TableCell>{String(supplier.supplierNumber || '')}</TableCell>
                        <TableCell>{String(supplier.phone || '-')}</TableCell>
                        <TableCell>{String(supplier.paymentTerms || '-')}</TableCell>
                        <TableCell className="text-right">
                          <span className={balance > 0 ? 'text-red-600 font-bold' : 'text-green-600'}>
                            {formatAmount(balance)}
                          </span>
                        </TableCell>
                      </TableRow>
                    )})
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
