import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { handleListSalesInvoices } from '@/lib/actions/sales-invoice.actions';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import { formatCurrency } from '@/lib/currency-formatter';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

export const metadata = { title: 'Customer Balances | Sales' };

type CustomerBalance = {
  customerId: string;
  customerName: string;
  invoicesCount: number;
  totalInvoiced: number;
  totalReceived: number;
  balanceDue: number;
};

export default async function BalancesPage() {
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const result = await handleListSalesInvoices({ take: 1000 });
  const invoices = result.success ? result.data?.items || [] : [];

  const balanceMap = invoices.reduce<Map<string, CustomerBalance>>((acc, invoice) => {
    const existing = acc.get(invoice.customerId) || {
      customerId: invoice.customerId,
      customerName: invoice.customerName,
      invoicesCount: 0,
      totalInvoiced: 0,
      totalReceived: 0,
      balanceDue: 0,
    };

    existing.invoicesCount += 1;
    existing.totalInvoiced += invoice.grandTotal;
    existing.totalReceived += invoice.amountReceived;
    existing.balanceDue += invoice.amountDue;

    acc.set(invoice.customerId, existing);
    return acc;
  }, new Map());

  const balances = Array.from(balanceMap.values()).sort((a, b) => b.balanceDue - a.balanceDue);
  const totalDue = balances.reduce((sum, row) => sum + row.balanceDue, 0);
  const currencySymbol = await getCurrencySymbolAsync();
  const fmt = (amount: number) => formatCurrency(amount, currencySymbol);

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>أرصدة الزبائن</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">عدد الزبائن</p>
              <p className="text-2xl font-bold">{balances.length}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">إجمالي الفواتير</p>
              <p className="text-2xl font-bold">{invoices.length}</p>
            </div>
            <div className="rounded-md border p-4">
              <p className="text-sm text-muted-foreground">إجمالي المستحق</p>
              <p className="text-2xl font-bold text-red-600">{fmt(totalDue)}</p>
            </div>
          </div>

          <div className="rounded-md border overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>الزبون</TableHead>
                  <TableHead>عدد الفواتير</TableHead>
                  <TableHead>إجمالي مفوتر</TableHead>
                  <TableHead>إجمالي مستلم</TableHead>
                  <TableHead className="text-right">الرصيد المستحق</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {balances.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center text-muted-foreground py-8">
                      لا توجد أرصدة لعرضها.
                    </TableCell>
                  </TableRow>
                ) : (
                  balances.map((row) => (
                    <TableRow key={row.customerId}>
                      <TableCell className="font-medium">{row.customerName}</TableCell>
                      <TableCell>{row.invoicesCount}</TableCell>
                      <TableCell>{fmt(row.totalInvoiced)}</TableCell>
                      <TableCell>{fmt(row.totalReceived)}</TableCell>
                      <TableCell className="text-right font-semibold text-red-600">
                        {fmt(row.balanceDue)}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
