import { verifySession } from '@/lib/auth';
import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import AdvancedReportsClient from '@/components/admin/reports/advanced-reports-client';
import type { SalesInvoice, CustomerPayment, InventoryMovement, JournalEntry } from '@/lib/types';
import type { MaterialFull, GroupLite } from '@/lib/reports/advanced-reporting';

export default async function AdvancedReportsPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global ?? {};

  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 {
    pgGetInvoices,
    pgGetPayments,
    pgGetInventoryMovements,
    pgGetJournalEntries,
    pgGetMaterials,
    pgGetItemGroups,
  } = await import('@/lib/postgres/data-access');

  const [
    invoicesResult,
    paymentsResult,
    movementsResult,
    journalEntriesResult,
    materialsResult,
    groupsResult,
    currencySymbol,
  ] = await Promise.all([
    pgGetInvoices({ page: 1, pageSize: 10000 }),
    pgGetPayments({ page: 1, pageSize: 10000 }),
    pgGetInventoryMovements({ page: 1, pageSize: 100000 }),
    pgGetJournalEntries({ page: 1, pageSize: 20000 }),
    pgGetMaterials({ page: 1, pageSize: 10000 }),
    pgGetItemGroups({ page: 1, pageSize: 5000 }),
    getCurrencySymbolAsync(),
  ]);

  const invoices = (invoicesResult.items || []) as SalesInvoice[];
  const payments = (paymentsResult.items || []) as CustomerPayment[];
  const inventoryMovements = (movementsResult.items || []) as InventoryMovement[];
  const journalEntries = (journalEntriesResult.items || []) as JournalEntry[];

  const materials: MaterialFull[] = (materialsResult.items || []).map((m: any) => ({
    id: String(m?.id || '').trim(),
    name: String(m?.name || '').trim(),
    purchasePrice: Number(m?.purchasePrice || 0),
    reorderMinimumQty: Number(m?.reorderMinimumQty || 0),
    groupId: String(m?.groupId || '').trim() || undefined,
  }));

  const groups: GroupLite[] = (groupsResult.items || []).map((g: any) => ({
    id: String(g?.id || '').trim(),
    name: String(g?.name || '').trim(),
  }));

  const defaultDate = new Date().toISOString().slice(0, 10);

  return (
    <AdvancedReportsClient
      invoices={invoices}
      payments={payments}
      inventoryMovements={inventoryMovements}
      journalEntries={journalEntries}
      materials={materials}
      groups={groups}
      currencySymbol={currencySymbol}
      defaultDate={defaultDate}
    />
  );
}
