import { verifySession } from '@/lib/auth';
import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import OperationalReportsClient from '@/components/admin/reports/operational-reports-client';
import type {
  Customer,
  CustomerPayment,
  InventoryMovement,
  JournalEntry,
  PurchaseOrder,
  SalesInvoice,
  SalesRep,
  Supplier,
} from '@/lib/types';

type MaterialLite = {
  id: string;
  name: string;
  purchasePrice?: number;
  reorderMinimumQty?: number;
};

type Props = {
  initialTab: string;
};

export default async function OperationsReportsView({ initialTab }: Props) {
  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 {
    pgGetCustomers,
    pgGetSuppliers,
    pgGetSalesReps,
    pgGetInvoices,
    pgGetPurchaseOrders,
    pgGetInventoryMovements,
    pgGetPayments,
    pgGetJournalEntries,
    pgGetMaterials,
    pgGetSettings,
  } = await import('@/lib/postgres/data-access');

  const [
    customersResult,
    suppliersResult,
    repsResult,
    invoicesResult,
    purchaseOrdersResult,
    movementsResult,
    paymentsResult,
    journalEntriesResult,
    materialsResult,
    settings,
    currencySymbol,
  ] = await Promise.all([
    pgGetCustomers({ page: 1, pageSize: 10000 }),
    pgGetSuppliers({ page: 1, pageSize: 10000 }),
    pgGetSalesReps({ page: 1, pageSize: 10000 }),
    pgGetInvoices({ page: 1, pageSize: 10000 }),
    pgGetPurchaseOrders({ page: 1, pageSize: 10000 }),
    pgGetInventoryMovements({ page: 1, pageSize: 100000 }),
    pgGetPayments({ page: 1, pageSize: 10000 }),
    pgGetJournalEntries({ page: 1, pageSize: 20000 }),
    pgGetMaterials({ page: 1, pageSize: 10000 }),
    pgGetSettings(),
    getCurrencySymbolAsync(),
  ]);

  const invoices = (invoicesResult.items || []) as SalesInvoice[];
  const purchaseOrders = (purchaseOrdersResult.items || []) as PurchaseOrder[];
  const inventoryMovements = (movementsResult.items || []) as InventoryMovement[];
  const payments = (paymentsResult.items || []) as CustomerPayment[];
  const journalEntries = (journalEntriesResult.items || []) as JournalEntry[];
  const customers = (customersResult.items || []) as Customer[];
  const suppliers = (suppliersResult.items || []) as Supplier[];
  const salesReps = (repsResult.items || []) as SalesRep[];

  const materials: MaterialLite[] = (materialsResult.items || []).map((material: any) => ({
    id: String(material?.id || '').trim(),
    name: String(material?.name || '').trim(),
    purchasePrice: Number(material?.purchasePrice || 0),
    reorderMinimumQty: Number(material?.reorderMinimumQty || 0),
  }));

  const posShiftSessions = Array.isArray((settings as any)?.posShiftSessions)
    ? ((settings as any).posShiftSessions as any[])
    : [];

  const defaultDate = new Date().toISOString().slice(0, 10);

  return (
    <OperationalReportsClient
      invoices={invoices}
      purchaseOrders={purchaseOrders}
      inventoryMovements={inventoryMovements}
      payments={payments}
      journalEntries={journalEntries}
      customers={customers}
      suppliers={suppliers}
      salesReps={salesReps}
      materials={materials}
      posShiftSessions={posShiftSessions}
      currencySymbol={currencySymbol}
      defaultDate={defaultDate}
      initialTab={initialTab}
    />
  );
}
