import { redirect } from 'next/navigation';

import PartyStatement from '@/components/admin/party-statement';
import { getSession } from '@/lib/auth';

import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import {
  pgGetCurrencies,
  pgGetCustomers,
  pgGetInvoices,
  pgGetPayments,
  pgGetSettings,
} from '@/lib/postgres/data-access';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import type { Currency } from '@/lib/types';

export const metadata = { title: 'Account Statement | Sales' };

interface StatementPageProps {
  searchParams?: Promise<{
    customerId?: string;
  }>;
}

export default async function StatementPage({ searchParams }: StatementPageProps) {
  const [session, locale] = await Promise.all([getSession(), getCurrentLocale()]);
  if (!session?.user) {
    redirect('/login');
  }

  const resolvedSearchParams = (await searchParams) || {};
  const selectedCustomerId = String(resolvedSearchParams.customerId || '').trim();
  const messages = (getTranslations(locale) ?? {}) as any;
  const tStatement = messages?.PartyStatement ?? {};
  const tGlobal = messages?.Global ?? {};

  let customers: any[] = [];
  let invoices: any[] = [];
  let customerPayments: any[] = [];
  let currencies: Currency[] = [];
  let settings: Record<string, unknown> = {};

  
  const [customersResult, invoicesResult, paymentsResult, currenciesResult, settingsResult] = await Promise.all([
  pgGetCustomers({ page: 1, pageSize: 5000 }),
  pgGetInvoices({ page: 1, pageSize: 5000 }),
  pgGetPayments({ page: 1, pageSize: 5000 }),
  pgGetCurrencies({ page: 1, pageSize: 500 }),
  pgGetSettings(),
  ]);

  customers = customersResult.items || [];
  invoices = invoicesResult.items || [];
  customerPayments = paymentsResult.items || [];
  currencies = (currenciesResult.items || []) as Currency[];
  settings = (settingsResult || {}) as Record<string, unknown>;
  

  const currencySymbol = await getCurrencySymbolAsync();

  return (
    <PartyStatement
      customers={customers}
      suppliers={[]}
      invoices={invoices}
      orders={[]}
      returns={[]}
      customerPayments={customerPayments}
      supplierPayments={[]}
      initialPartyId={selectedCustomerId ? `customer:${selectedCustomerId}` : undefined}
      t={tStatement}
      tGlobal={tGlobal}
      locale={locale}
      currencySymbol={currencySymbol}
      currencies={currencies}
      printingSettings={{
        printHeaderLeftText: String(settings?.printHeaderLeftText || ''),
        printHeaderCenterText: String(settings?.printHeaderCenterText || ''),
        printHeaderRightText: String(settings?.printHeaderRightText || ''),
        printHeaderText: String(settings?.printHeaderText || ''),
        printFooterText: String(settings?.printFooterText || ''),
      }}
    />
  );
}
