import { verifySession } from "@/lib/auth";

import { hasEmployeePermission } from "@/lib/employee-permissions";
import { pgGetInternalTransfers, pgGetInventoryMovements, pgGetMaterials, pgGetActiveWarehouses } from "@/lib/postgres/data-access";
import { getCurrentLocale, getTranslations } from "@/lib/i18n";
import InternalTransferDocuments from "@/components/admin/internal-transfer-documents";
import type { InternalTransferDocument, ProductionItem, StockLocationBalance, Warehouse } from "@/lib/types";

export default async function InternalTransfersPage({
  searchParams,
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  await searchParams;
  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 settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();

  if (!user || !hasEmployeePermission(user, settings, 'admin.materials')) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal?.accessDenied ?? "الوصول مرفوض"}</h1>
        <p>{tGlobal?.noPermission ?? "ليس لديك صلاحية لعرض هذه الصفحة."}</p>
      </div>
    );
  }

  const documents: InternalTransferDocument[] = (await pgGetInternalTransfers({ page: 1, pageSize: 5000 })).items as InternalTransferDocument[];
  const materials: ProductionItem[] = (await pgGetMaterials({ page: 1, pageSize: 5000 })).items as ProductionItem[];
  const warehouses: Warehouse[] = (await pgGetActiveWarehouses()).items as Warehouse[];
  const materialIds = materials.map((m) => m.id);
  const stockLocationsByMaterial = (((await pgGetInventoryMovements({ page: 1, pageSize: 10000 })).items || []) as Array<Record<string, unknown>>)
        .reduce<Record<string, StockLocationBalance[]>>((acc, movement) => {
          const materialId = String(movement.materialId || '').trim();
          const warehouseId = String(movement.warehouseId || '').trim();
          const shelfId = String(movement.shelfId || '').trim();
          if (!materialId || !materialIds.includes(materialId) || !warehouseId || !shelfId) {
            return acc;
          }

          const quantityIn = Number(movement.quantityIn || 0);
          const quantityOut = Number(movement.quantityOut || 0);
          const netQuantity = quantityIn - quantityOut;
          if (!Number.isFinite(netQuantity) || netQuantity === 0) {
            return acc;
          }

          const warehouse = warehouses.find((entry) => String(entry.id || '').trim() === warehouseId);
          const shelf = (warehouse?.shelves || []).find((entry) => String(entry.id || '').trim() === shelfId);
          const existing = acc[materialId] || [];
          const match = existing.find((entry) => entry.warehouseId === warehouseId && entry.shelfId === shelfId);

          if (match) {
            match.quantity += netQuantity;
          } else {
            existing.push({
              materialId,
              warehouseId,
              warehouseName: warehouse?.name || warehouseId,
              shelfId,
              shelfName: shelf?.name || shelfId,
              quantity: netQuantity,
            });
            acc[materialId] = existing;
          }

          return acc;
        }, {});

  const allowedWarehouseIds = undefined;

  return (
    <div className="w-full max-w-[96vw] 2xl:max-w-[1800px] mx-auto">
      <InternalTransferDocuments
        documents={documents}
        materials={materials}
        warehouses={warehouses}
        stockLocationsByMaterial={stockLocationsByMaterial}
        allowedWarehouseIds={allowedWarehouseIds}
      />
      <p className="mt-2 text-xs text-muted-foreground">
        {tLists?.internalTransfersDescription ?? "سجل نقل الاصناف بين الرفوف والمستودعات."}
      </p>
    </div>
  );
}
