import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import {
  handleListSalesInvoices,
  handleListSalesPaymentReceipts,
} from '@/lib/actions/sales-invoice.actions';

import SalesPaymentReceivedClient from '@/components/admin/sales/sales-payment-received-client';

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

type PaymentPageProps = {
  searchParams?: Promise<{ editId?: string }>;
};

export default async function PaymentPage({ searchParams }: PaymentPageProps) {
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const resolvedSearchParams = (await searchParams) || {};
  const editPaymentId = String(resolvedSearchParams.editId || '').trim() || undefined;

  const result = await handleListSalesInvoices({ take: 300 });
  const invoices = result.success ? result.data?.items || [] : [];

  const paymentReceiptsResult = await handleListSalesPaymentReceipts({ take: 200 });
  const payments = paymentReceiptsResult.success ? paymentReceiptsResult.data?.items || [] : [];

  const rawCurrencies: any[] = (await (await import('@/lib/postgres/data-access')).pgGetCurrencies({ page: 1, pageSize: 5000 })).items;

  // Fetch general banks for checks (not company bank accounts)
  const rawGeneralBanks: any[] = await (await import('@/lib/postgres/data-access')).pgGetGeneralBanks();

  // Still fetch company banks for compatibility (may be used elsewhere)
  const rawBanks: any[] = (await (await import('@/lib/postgres/data-access')).pgGetBanks({ page: 1, pageSize: 5000 })).items;

  const defaultCurrency = await (await import('@/lib/postgres/data-access')).pgGetDefaultCurrency();

  const currencies = (rawCurrencies || []).filter((entry) => entry && typeof entry.code === 'string');
  const generalBanks = (rawGeneralBanks || []).filter((entry) => entry && typeof entry.id === 'string' && entry.isActive !== false);
  const banks = (rawBanks || []).filter((entry) => entry && typeof entry.id === 'string');
  const defaultCurrencyCode = String(defaultCurrency?.code || 'JOD');

  return (
    <SalesPaymentReceivedClient
      invoices={invoices}
      payments={payments as any}
      currencies={currencies as any}
      banks={generalBanks as any}  // Pass general banks for check selection
      defaultCurrencyCode={defaultCurrencyCode}
      editPaymentId={editPaymentId}
      userId={session.user.id}
      userName={session.user.name}
    />
  );
}
