import { verifySession } from "@/lib/auth";

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";

type PageProps = {
  params: Promise<{ id: string }>;
  searchParams?: Promise<{ [key: string]: string | string[] | undefined }>;
};

export default async function InternalTransferDocumentViewPage({ params, searchParams }: PageProps) {
  const { id } = await params;
  const resolvedSearch = searchParams ? await searchParams : {};
  const editMode = resolvedSearch?.edit === '1';
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  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 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 = user.role === 'admin' ? undefined : user.warehouseIds ?? [];

  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}
        focusDocId={String(id)}
        inlineEditDocId={editMode ? String(id) : undefined}
      />
      <p className="mt-2 text-xs text-muted-foreground">
        {tLists?.internalTransfersDescription ?? "سجل نقل الاصناف بين الرفوف والمستودعات."}
      </p>
    </div>
  );
}
