import PurchaseReturnForm from "@/components/admin/purchase-return-form";
import { verifySession } from "@/lib/auth";

import { hasEmployeePermission } from "@/lib/employee-permissions";
import { getCurrentLocale, getTranslations } from "@/lib/i18n";
import PurchaseReturnList from "@/components/admin/purchase-return-list";
import type { StockLocationBalance } from "@/lib/types";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

export default async function PurchaseReturnsPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const isRtl = locale === 'ar';
  const t = getTranslations(locale);
  const tPurchases = t.Purchases ?? {};
  const tGlobal = t.Global ?? {};

  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings() as any;

  if (!user || !hasEmployeePermission(user, settings, 'admin.purchases')) {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal.accessDenied}</h1>
        <p>{tGlobal.noPermission}</p>
      </div>
    );
  }

  let purchaseOrders = [];
  let returns = [];
  let suppliers = [];
  let materials = [];
  let baseCurrency = undefined;
  let runtimeSettings = ({} as any);
  let warehousesEnabled = settings.warehousesEnabled === true || settings.warehousesEnabled === 'true';
  let warehouses = [];
  let movementEntries = [];

  
  const {
  pgGetPurchaseOrders,
  pgGetPurchaseReturns,
  pgGetSuppliers,
  pgGetMaterials,
  pgGetDefaultCurrency,
  pgGetSettings,
  pgGetActiveWarehouses,
  pgGetInventoryMovements,
  pgGetInternalTransfers,
  } = await import('@/lib/postgres/data-access');

  const [
  purchaseOrdersResult,
  returnsResult,
  suppliersResult,
  materialsResult,
  baseCurrencyResult,
  settingsResult,
  warehousesResult,
  movementsResult,
  internalTransfersResult,
  ] = await Promise.all([
  pgGetPurchaseOrders({ page: 1, pageSize: 5000 }),
  pgGetPurchaseReturns({ page: 1, pageSize: 5000 }),
  pgGetSuppliers({ page: 1, pageSize: 5000 }),
  pgGetMaterials({ page: 1, pageSize: 5000 }),
  pgGetDefaultCurrency(),
  pgGetSettings(),
  pgGetActiveWarehouses(),
  pgGetInventoryMovements({ page: 1, pageSize: 10000 }),
  pgGetInternalTransfers({ page: 1, pageSize: 5000 }),
  ]);

  purchaseOrders = (purchaseOrdersResult.items || []) as typeof purchaseOrders;
  returns = (returnsResult.items || []) as typeof returns;
  suppliers = (suppliersResult.items || []) as typeof suppliers;
  materials = (materialsResult.items || []) as typeof materials;
  baseCurrency = (baseCurrencyResult as typeof baseCurrency) || baseCurrency;
  runtimeSettings = (settingsResult as typeof runtimeSettings) || runtimeSettings;
  warehousesEnabled = runtimeSettings.warehousesEnabled === true || runtimeSettings.warehousesEnabled === 'true';
  warehouses = warehousesEnabled ? ((warehousesResult.items || []) as typeof warehouses) : [];
  const internalTransferDocuments = warehousesEnabled
    ? ((internalTransfersResult.items || []) as Array<Record<string, any>>)
    : [];
  movementEntries = warehousesEnabled
  ? (((movementsResult.items || []) as Array<Record<string, unknown>>).map((movement) => ({
      referenceType: String(movement.referenceType || ''),
      materialId: String(movement.materialId || ''),
      warehouseId: String(movement.warehouseId || ''),
      shelfId: String(movement.shelfId || ''),
      quantity:
        Number(movement.quantityIn || 0) > 0
          ? Number(movement.quantityIn || 0)
          : Number(movement.quantityOut || 0),
      direction: Number(movement.quantityOut || 0) > 0 ? 'out' : 'in',
    })) as typeof movementEntries)
  : [];
  

  const allowedWarehouseIds = warehousesEnabled
    ? new Set((user.warehouseIds || []).map((id) => String(id || '').trim()).filter(Boolean))
    : new Set<string>();
  const restrictByWarehouse = warehousesEnabled && user.role !== 'admin' && allowedWarehouseIds.size > 0;

  const warehouseNameById = new Map(warehouses.map((wh) => [wh.id, wh.name]));
  const shelfNameByWarehouseAndId = new Map<string, string>();
  warehouses.forEach((wh) => {
    (wh.shelves || []).forEach((shelf) => {
      shelfNameByWarehouseAndId.set(`${wh.id}||${shelf.id}`, shelf.name);
    });
  });

  const transferRefTypes = new Set([
    'transfer_document',
    'transfer-doc',
    'transfer_doc',
    'internal_transfer_doc',
    'transfer_document_receipt',
    'transfer_document_nullified',
    'transfer_document_reversal',
    'transfer_document_cancel',
  ]);

  const addToBalances = (
    acc: Map<string, number>,
    materialId?: string,
    warehouseId?: string,
    shelfId?: string,
    qty?: number,
  ) => {
    const mat = String(materialId || '').trim();
    const wh = String(warehouseId || '').trim();
    const shelf = String(shelfId || '').trim();
    const amount = Number(qty || 0);
    if (!mat || !wh || !shelf || !Number.isFinite(amount) || amount === 0) return;
    if (restrictByWarehouse && !allowedWarehouseIds.has(wh)) return;
    const key = `${mat}||${wh}||${shelf}`;
    acc.set(key, (acc.get(key) || 0) + amount);
  };

  const stockByMaterialAndLocation = movementEntries.reduce<Map<string, number>>((acc, mv) => {
    const materialId = String(mv.materialId || '').trim();
    const warehouseId = String(mv.warehouseId || '').trim();
    const shelfId = String(mv.shelfId || '').trim();
    const quantity = Number(mv.quantity || 0);
    const referenceType = String((mv as any).referenceType || '').trim().toLowerCase();
    if (restrictByWarehouse && !allowedWarehouseIds.has(warehouseId)) return acc;
    if (!materialId || !warehouseId || !shelfId || !Number.isFinite(quantity) || quantity <= 0) return acc;

    // Ignore transfer document movements from raw log and rebuild them from canonical documents.
    if (transferRefTypes.has(referenceType)) return acc;

    const key = `${materialId}||${warehouseId}||${shelfId}`;
    const signedQty = mv.direction === 'out' ? -quantity : quantity;
    acc.set(key, (acc.get(key) || 0) + signedQty);
    return acc;
  }, new Map<string, number>());

  // Rebuild transfer-document effects from canonical internal transfer documents.
  internalTransferDocuments
    .filter((doc) => String(doc.status || 'active') === 'active')
    .forEach((doc) => {
      const receiptStatus = String(doc.receiptStatus || 'pending').trim();
      (doc.items || []).forEach((item: any) => {
        const baseReceived = receiptStatus === 'pending'
          ? Number(item.quantity || 0)
          : Number(item.receivedQuantity ?? item.quantity ?? 0);
        const overApproved = Number(
          item.overApprovedQuantity ?? (item.overageStatus === 'approved' ? item.overReceivedQuantity ?? 0 : 0)
        );
        const safeBaseReceived = Math.max(0, baseReceived);
        const safeOverApproved = Math.max(0, overApproved);
        const toWarehouseId = doc.enableWarehouseTransfer ? item.toWarehouseId : item.fromWarehouseId;
        const toShelfId = doc.enableShelfTransfer ? item.toShelfId : item.fromShelfId;
        const savedDistributions = Array.isArray(item.receiptDistributions)
          ? item.receiptDistributions
              .map((entry: any) => ({
                shelfId: String(entry?.shelfId || '').trim(),
                quantity: Number(entry?.quantity || 0),
              }))
              .filter((entry: any) => entry.shelfId && Number.isFinite(entry.quantity) && entry.quantity > 0)
          : [];

        if (safeBaseReceived > 0) {
          addToBalances(stockByMaterialAndLocation, item.materialId, item.fromWarehouseId, item.fromShelfId, -safeBaseReceived);

          if (savedDistributions.length > 0 && receiptStatus !== 'pending') {
            const distributedTotal = savedDistributions.reduce((sum: number, entry: any) => sum + entry.quantity, 0);
            const factor = distributedTotal > 0 ? safeBaseReceived / distributedTotal : 0;
            savedDistributions.forEach((entry: any) => {
              addToBalances(stockByMaterialAndLocation, item.materialId, toWarehouseId, entry.shelfId, entry.quantity * factor);
            });
          } else {
            addToBalances(stockByMaterialAndLocation, item.materialId, toWarehouseId, toShelfId, safeBaseReceived);
          }
        }

        if (safeOverApproved > 0) {
          const overageSourceShelfId = item.overageSourceShelfId || item.fromShelfId;
          addToBalances(stockByMaterialAndLocation, item.materialId, item.fromWarehouseId, overageSourceShelfId, -safeOverApproved);

          if (savedDistributions.length > 0 && receiptStatus !== 'pending') {
            const distributedTotal = savedDistributions.reduce((sum: number, entry: any) => sum + entry.quantity, 0);
            const factor = distributedTotal > 0 ? safeOverApproved / distributedTotal : 0;
            savedDistributions.forEach((entry: any) => {
              addToBalances(stockByMaterialAndLocation, item.materialId, toWarehouseId, entry.shelfId, entry.quantity * factor);
            });
          } else {
            addToBalances(stockByMaterialAndLocation, item.materialId, toWarehouseId, toShelfId, safeOverApproved);
          }
        }
      });
    });

  const stockLocationsByMaterial = Array.from(stockByMaterialAndLocation.entries()).reduce<Record<string, StockLocationBalance[]>>((acc, [key, quantity]) => {
    if (quantity <= 0) return acc;
    const [materialId, warehouseId, shelfId] = key.split('||');
    if (!materialId || !warehouseId || !shelfId) return acc;
    const list = acc[materialId] || [];
    list.push({
      materialId,
      warehouseId,
      shelfId,
      quantity,
      warehouseName: warehouseNameById.get(warehouseId) || warehouseId,
      shelfName: shelfNameByWarehouseAndId.get(`${warehouseId}||${shelfId}`) || shelfId,
    });
    acc[materialId] = list;
    return acc;
  }, {});

  const visiblePurchaseOrders = restrictByWarehouse
    ? purchaseOrders.filter((order) => {
        const warehouseId = String(order.warehouseId || '').trim();
        return warehouseId ? allowedWarehouseIds.has(warehouseId) : false;
      })
    : purchaseOrders;

  return (
    <div dir={isRtl ? 'rtl' : 'ltr'} className={isRtl ? 'text-right' : 'text-left'}>
      <Tabs defaultValue="create" className="w-full">
      <TabsList className="grid w-full grid-cols-2">
        <TabsTrigger value="create">{tPurchases.createReturn ?? "إنشاء مردود مشتريات"}</TabsTrigger>
        <TabsTrigger value="list">{tPurchases.showReturns ?? "عرض مردودات المشتريات"}</TabsTrigger>
      </TabsList>

      <TabsContent value="create" className="space-y-4">
        <PurchaseReturnForm
          orders={visiblePurchaseOrders}
          returns={returns}
          materials={materials}
          warehouses={warehouses}
          stockLocationsByMaterial={stockLocationsByMaterial}
          t={tPurchases}
          tGlobal={tGlobal}
          isRtl={isRtl}
        />
      </TabsContent>

      <TabsContent value="list" className="space-y-4">
        <PurchaseReturnList
          returns={returns}
          suppliers={suppliers}
          currencyCode={baseCurrency?.code || 'USD'}
          t={tPurchases}
        />
      </TabsContent>
      </Tabs>
    </div>
  );
}
