import { verifySession } from '@/lib/auth';
import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import { getChartOfAccountsWithSeedMerge } from '@/lib/accounting/chart-of-accounts-runtime';
import FinancialReportsClient from '@/components/admin/reports/financial-reports-client';
import type { JournalEntry } from '@/lib/types';
import type { FinancialReportAccount, FinancialReportJournalEntry } from '@/lib/accounting/financial-reporting';

export default async function FinancialReportsPage() {
  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 { pgGetJournalEntries } = await import('@/lib/postgres/data-access');

  const [accounts, journalEntriesResult, currencySymbol] = await Promise.all([
    getChartOfAccountsWithSeedMerge(),
    pgGetJournalEntries({ page: 1, pageSize: 10000 }),
    getCurrencySymbolAsync(),
  ]);

  const serializedAccounts: FinancialReportAccount[] = (accounts || [])
    .filter((account) => !account.inactive)
    .map((account) => ({
      id: String(account.id || '').trim(),
      code: String(account.code || '').trim(),
      nameAr: String(account.nameAr || '').trim(),
      nameEn: String(account.nameEn || '').trim(),
      type: account.type,
      parentId: account.parentId ? String(account.parentId).trim() : null,
      nature: account.nature === 'credit' ? 'credit' : 'debit',
      inactive: account.inactive === true,
    }));

  const serializedEntries: FinancialReportJournalEntry[] = (((journalEntriesResult.items || []) as JournalEntry[])
    .map((entry) => ({
      id: String(entry.id || '').trim(),
      date: String(entry.date || '').trim(),
      description: String(entry.description || '').trim(),
      status: entry.status === 'draft' ? 'draft' : 'posted',
      referenceType: entry.referenceType,
      referenceId: String(entry.referenceId || '').trim(),
      createdBy: String(entry.createdBy || '').trim(),
      lines: (Array.isArray(entry.lines) ? entry.lines : []).map((line) => ({
        accountId: String(line.accountId || '').trim(),
        accountCode: String(line.accountCode || '').trim(),
        accountName: String(line.accountName || '').trim(),
        debit: Number(line.debit || 0),
        credit: Number(line.credit || 0),
        description: String(line.description || '').trim(),
      })),
    })));

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

  return (
    <FinancialReportsClient
      accounts={serializedAccounts}
      entries={serializedEntries}
      currencySymbol={currencySymbol}
      defaultDate={defaultDate}
    />
  );
}
