import { verifySession } from "@/lib/auth";
import {
  pgGetCustomerCategories,
  pgGetItemGroups,
  pgGetManagedUnits,
  pgGetMaterialById,
  pgGetMaterialsForEditor,
  pgGetMaterialsForEditorByIds,
  pgGetProductShapeDefinitions,
  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 MaterialEditPageClient from "@/components/admin/material-edit-page-client";
import { handleGetRealEstateProjects } from "@/lib/actions";
import type {
  ChartOfAccount,
  CustomerCategory,
  ItemGroup,
  ManagedUnit,
  ProductionItem,
  RealEstateProject,
  Warehouse,
} from "@/lib/types";

export default async function EditMaterialPage({ params }: { params: Promise<{ id: string }> }) {
  const [session, locale, currencySymbol] = await Promise.all([
    verifySession(),
    getCurrentLocale(),
    getCurrencySymbolAsync(),
  ]);
  const user = session.user;
  const t = getTranslations(locale);
  const tGlobal = t.Global || {};
  const tLists = t.ItemLists || {};

  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 resolvedParams = await params;
  const materialId = decodeURIComponent(String(resolvedParams?.id || '')).trim();
  if (!materialId) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.error ?? "خطأ"}</h1>
        <p>{tLists?.itemNotFoundLabel || "الصنف غير موجود."}</p>
      </div>
    );
  }

  const [
    item,
    chartOfAccounts,
    materialsResult,
    categoriesResult,
    itemGroupsResult,
    unitDefinitionsResult,
    productShapeDefinitionsResult,
    realEstateProjectsResult,
    warehousesResult,
  ] = await Promise.all([
    pgGetMaterialById(materialId),
    getChartOfAccountsWithSeedMerge(),
    pgGetMaterialsForEditor({ pageSize: 5000, excludeId: materialId }),
    pgGetCustomerCategories({ page: 1, pageSize: 5000 }),
    pgGetItemGroups({ page: 1, pageSize: 5000 }),
    pgGetManagedUnits({ page: 1, pageSize: 5000 }),
    pgGetProductShapeDefinitions({ page: 1, pageSize: 5000 }),
    handleGetRealEstateProjects(),
    pgGetWarehouses({ page: 1, pageSize: 5000 }),
  ]);

  const materialItem = item as ProductionItem | null;
  if (!materialItem) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.error ?? "خطأ"}</h1>
        <p>{tLists?.itemNotFoundLabel || "الصنف غير موجود."}</p>
      </div>
    );
  }

  const materials: ProductionItem[] = ((materialsResult.items || []) as ProductionItem[]);

  const selectedAlternativeIds = Array.from(
    new Set(
      (Array.isArray(materialItem.alternativeItemIds) ? materialItem.alternativeItemIds : [])
        .map((value) => String(value || '').trim())
        .filter((value) => value && value !== materialId)
    )
  );

  // Pull a similarity pool from server search so smart alternative suggestions
  // can find strong matches outside the first page window.
  const itemNameQuery = String(materialItem.name || '').trim();
  const [similarityPoolResult, selectedAlternativesResult] = await Promise.all([
    itemNameQuery
      ? pgGetMaterialsForEditor({ pageSize: 300, search: itemNameQuery, excludeId: materialId })
      : Promise.resolve({ items: [] as unknown[] }),
    selectedAlternativeIds.length > 0
      ? pgGetMaterialsForEditorByIds(selectedAlternativeIds, { excludeId: materialId })
      : Promise.resolve({ items: [] as unknown[] }),
  ]);
  const similarityPool = ((similarityPoolResult.items || []) as ProductionItem[]);
  const selectedAlternativesPool = ((selectedAlternativesResult.items || []) as ProductionItem[]);

  const mergedById = new Map<string, ProductionItem>();
  [materialItem, ...materials, ...similarityPool, ...selectedAlternativesPool].forEach((entry) => {
    const id = String(entry?.id || '').trim();
    if (!id) return;
    if (!mergedById.has(id)) mergedById.set(id, entry);
  });
  const materialsForEditor: ProductionItem[] = Array.from(mergedById.values());

  const realEstateProjects: RealEstateProject[] = realEstateProjectsResult && 'success' in realEstateProjectsResult && realEstateProjectsResult.success
    ? (((realEstateProjectsResult as any).items || []) as RealEstateProject[])
    : [];
  const categories = categoriesResult.items as CustomerCategory[];
  const itemGroups = itemGroupsResult.items as ItemGroup[];
  const unitDefinitions = unitDefinitionsResult.items as ManagedUnit[];
  const productShapeDefinitions = productShapeDefinitionsResult.items as Array<Record<string, unknown>>;
  const warehouses: Warehouse[] = warehousesResult.items as Warehouse[];

  return (
    <MaterialEditPageClient
      item={materialItem}
      items={materialsForEditor}
      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 as ChartOfAccount[]}
      currencySymbol={currencySymbol}
    />
  );
}
