import { IncomingChecksClient } from '@/components/admin/incoming-checks-client';
import DashboardLayout from '@/components/layout/dashboard-layout';
import Link from 'next/link';
import { Button } from '@/components/ui/button';

import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { pgGetChecksReceived, pgGetCustomers, pgGetSettings, pgGetSuppliers } from '@/lib/postgres/data-access';
import { getChartOfAccountsWithSeedMerge } from '@/lib/accounting/chart-of-accounts-runtime';

export default async function IncomingChecksPage() {
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const [settings, checksResult, customersResult, suppliersResult] = await Promise.all([
    pgGetSettings(),
    pgGetChecksReceived({ page: 1, pageSize: 5000 }),
    pgGetCustomers({ page: 1, pageSize: 5000 }),
    pgGetSuppliers({ page: 1, pageSize: 5000 }),
  ]);
  const chartAccounts = await getChartOfAccountsWithSeedMerge();
  const hasIncomingChecksAccount = chartAccounts.some((acc: any) => String(acc?.code || '').trim() === '1015' && !acc?.inactive);
  const hasCollectionChecksAccount = chartAccounts.some((acc: any) => String(acc?.code || '').trim() === '1020' && !acc?.inactive);
  const collectionAccountsReady = hasIncomingChecksAccount && hasCollectionChecksAccount;
  const currencySymbol = String(settings?.currency || settings?.appCurrency || '$');

  const checks = (checksResult.items || []);
  const customers = (customersResult.items || []);
  const suppliers = (suppliersResult.items || []);

  const incomingChecksText = (t as any)?.IncomingChecksPage || {};

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">{incomingChecksText.title ?? 'الشيكات الواردة'}</h1>
            <p className="text-sm text-muted-foreground">
              {incomingChecksText.description ?? 'إدارة الشيكات الواردة من العملاء ومتابعة حالتها وتجييرها.'}
            </p>
          </div>
          <Link href="/admin/checks/endorsed">
            <Button variant="outline">
              تقرير الشيكات المجيّرة
            </Button>
          </Link>
        </div>
        <IncomingChecksClient
          checks={checks as any[]}
          customers={customers as any[]}
          suppliers={suppliers as any[]}
          collectionAccountsReady={collectionAccountsReady}
          t={incomingChecksText}
          currencySymbol={currencySymbol}
        />
      </div>
    </DashboardLayout>
  );
}
