import { verifySession } from '@/lib/auth';
import { getTranslations, getCurrentLocale } from '@/lib/i18n';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import RealEstateCostingManager from '@/components/admin/real-estate-costing-manager';
import type { Customer, JournalEntry, ProductionItem, PurchaseOrder, RealEstateAccountingSetup, RealEstateProject } from '@/lib/types';
import { pgGetCustomers, pgGetExpenses, pgGetJournalEntries, pgGetMaterials, pgGetPurchaseOrders, pgGetSettings } from '@/lib/postgres/data-access';

export default async function RealEstatePage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global || {};
  const tItemLists = t.ItemLists || {};
  const currencySymbol = await getCurrencySymbolAsync();

  if (!user || user.role !== 'admin') {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? 'الوصول مرفوض'}</h1>
        <p>{tGlobal?.noPermission ?? 'ليس لديك صلاحية لعرض هذه الصفحة.'}</p>
      </div>
    );
  }

  const settings = await pgGetSettings();  const businessMode = String(settings?.businessMode || '').trim();
  const realEstateEnabled = businessMode === 'real-estate' || businessMode === 'hybrid' || settings?.realEstateEnabled === true || settings?.realEstateEnabled === 'true';

  if (!realEstateEnabled) {
    return (
      <div className="rounded-md border border-dashed p-6 text-center text-muted-foreground">
        <h1 className="text-xl font-semibold text-foreground">{tItemLists?.realEstateProjectsTitle ?? 'المشاريع العقارية'}</h1>
        <p className="mt-2">{tItemLists?.realEstateFeatureDisabled ?? 'هذه الميزة معطلة حاليًا من الإعدادات العامة.'}</p>
      </div>
    );
  }

  const { handleGetRealEstateProjects } = await import('@/lib/actions');
  const projectsResult = await handleGetRealEstateProjects();
  const accountingSetup: RealEstateAccountingSetup | undefined = projectsResult && 'success' in projectsResult && projectsResult.success
    ? ((projectsResult as any).accountingSetup as RealEstateAccountingSetup)
    : undefined;
  const projects: RealEstateProject[] = projectsResult && 'success' in projectsResult && projectsResult.success
    ? (((projectsResult as any).items || []) as RealEstateProject[])
    : [];
  const materials: ProductionItem[] = (await pgGetMaterials({ page: 1, pageSize: 5000 })).items as ProductionItem[];
  const expenses: ProductionItem[] = (await pgGetExpenses({ page: 1, pageSize: 5000 })).items as ProductionItem[];
  const journalEntries: JournalEntry[] = (await pgGetJournalEntries({ page: 1, pageSize: 5000 })).items as JournalEntry[];
  const customers: Customer[] = (await pgGetCustomers({ page: 1, pageSize: 5000 })).items as Customer[];
  const purchaseOrders: PurchaseOrder[] = (await pgGetPurchaseOrders({ page: 1, pageSize: 5000 })).items as PurchaseOrder[];

  return (
    <div className="w-full">
      <RealEstateCostingManager
        initialProjects={projects}
        materials={materials}
        expenses={expenses}
        journalEntries={journalEntries}
        accountingSetup={accountingSetup}
        customers={customers}
        purchaseOrders={purchaseOrders}
        t={tItemLists}
        tGlobal={tGlobal}
        currencySymbol={currencySymbol}
      />
    </div>
  );
}
