import { verifySession } from "@/lib/auth";
import {
  pgGetCustomerCategories,
  pgGetItemGroups,
  pgGetManagedUnits,
  pgGetMaterials,
  pgGetProductShapeDefinitions,
  pgGetSettings,
  pgGetWarehouses,
} from "@/lib/postgres/data-access";
import { getTranslations, getCurrentLocale } from "@/lib/i18n";
import { getCurrencySymbolAsync } from "@/lib/server-currency";
import { getChartOfAccountsWithSeedMerge } from "@/lib/accounting/chart-of-accounts-runtime";
import MaterialAddPageClient from "@/components/admin/material-add-page-client";
import type {
  ChartOfAccount,
  CustomerCategory,
  ItemGroup,
  ManagedUnit,
  ProductionItem,
  RealEstateProject,
  Warehouse,
} from "@/lib/types";

export default async function AddMaterialPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global || {};
  const tLists = t.ItemLists || {};
  const currencySymbol = await getCurrencySymbolAsync();
  const chartOfAccounts = (await getChartOfAccountsWithSeedMerge()) as ChartOfAccount[];

  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 materials: ProductionItem[] = (await pgGetMaterials({ page: 1, pageSize: 5000 })).items as ProductionItem[];

  const [categories, itemGroups, unitDefinitions, productShapeDefinitions]: [
    CustomerCategory[],
    ItemGroup[],
    ManagedUnit[],
    Array<Record<string, unknown>>
  ] = [
    (await pgGetCustomerCategories({ page: 1, pageSize: 5000 })).items as CustomerCategory[],
    (await pgGetItemGroups({ page: 1, pageSize: 5000 })).items as ItemGroup[],
    (await pgGetManagedUnits({ page: 1, pageSize: 5000 })).items as ManagedUnit[],
    (await pgGetProductShapeDefinitions({ page: 1, pageSize: 5000 })).items as Array<Record<string, unknown>>,
  ];

  const settings = await pgGetSettings();

  const realEstateProjectsResult = await (await import('@/lib/actions')).handleGetRealEstateProjects();
  const realEstateProjects: RealEstateProject[] = realEstateProjectsResult && 'success' in realEstateProjectsResult && realEstateProjectsResult.success
    ? (((realEstateProjectsResult as any).items || []) as RealEstateProject[])
    : [];

  const warehouses: Warehouse[] = (await pgGetWarehouses({ page: 1, pageSize: 5000 })).items as Warehouse[];

  return (
    <MaterialAddPageClient
      items={materials}
      t={tLists}
      tGlobal={tGlobal}
      categories={categories}
      itemGroups={itemGroups}
      unitDefinitions={unitDefinitions}
      warehouses={warehouses}
      productShapeDefinitions={productShapeDefinitions
        .map((entry) => ({ id: String(entry.id || ""), name: String(entry.name || "").trim() }))
        .filter((entry) => entry.id && entry.name)}
      realEstateProjects={realEstateProjects}
      chartOfAccounts={chartOfAccounts}
      currencySymbol={currencySymbol}
    />
  );
}
