import { verifySession } from '@/lib/auth';
import { getTranslations, getCurrentLocale } from '@/lib/i18n';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import DisassemblyManager from '@/components/admin/disassembly-manager';
import type { DisassemblyRecord, ProductionItem, StockLocationBalance, Warehouse } from '@/lib/types';
import {
  pgGetInventoryMovements,
  pgGetMaterials,
  pgGetSettings,
  pgGetWarehouses,
} from '@/lib/postgres/data-access';

export default async function DisassemblyPage() {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global || {};
  const tItemLists = t.ItemLists || {};
  const currencySymbol = await getCurrencySymbolAsync();

  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 settings = await pgGetSettings();

  const warehousesEnabled = settings.warehousesEnabled === true || settings.warehousesEnabled === 'true';
  const warehouses: Warehouse[] = (await pgGetWarehouses({ page: 1, pageSize: 5000 })).items as Warehouse[];

  const records: DisassemblyRecord[] = Array.isArray((settings as any)?.disassemblyRecords)
    ? ((settings as any).disassemblyRecords as DisassemblyRecord[])
    : [];

  let stockLocationsByMaterial: Record<string, StockLocationBalance[]> = {};
  if (warehousesEnabled) {
    
    const inventoryMovements = (((await pgGetInventoryMovements({ page: 1, pageSize: 10000 })).items || []) as Array<Record<string, unknown>>);
    const warehouseNameById = new Map(warehouses.map((warehouse) => [warehouse.id, warehouse.name]));
    const shelfNameByCompositeId = new Map<string, string>();

    warehouses.forEach((warehouse) => {
    (warehouse.shelves || []).forEach((shelf) => {
      shelfNameByCompositeId.set(`${warehouse.id}||${shelf.id}`, shelf.name);
    });
    });

    const balances = inventoryMovements.reduce<Map<string, number>>((acc, movement) => {
    const materialId = String(movement.materialId || '').trim();
    const warehouseId = String(movement.warehouseId || '').trim();
    const shelfId = String(movement.shelfId || '').trim();
    const quantity = Number(movement.quantityIn || 0) - Number(movement.quantityOut || 0);

    if (!materialId || !warehouseId || !shelfId || !Number.isFinite(quantity) || quantity === 0) {
      return acc;
    }

    const key = `${materialId}||${warehouseId}||${shelfId}`;
    acc.set(key, (acc.get(key) || 0) + quantity);
    return acc;
    }, new Map<string, number>());

    stockLocationsByMaterial = Array.from(balances.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,
      warehouseName: warehouseNameById.get(warehouseId) || warehouseId,
      shelfId,
      shelfName: shelfNameByCompositeId.get(`${warehouseId}||${shelfId}`) || shelfId,
      quantity,
    });
    acc[materialId] = list;
    return acc;
    }, {});
    
  }

  return (
    <div className="w-full">
      <DisassemblyManager
        materials={materials}
        warehouses={warehouses}
        warehousesEnabled={warehousesEnabled}
        stockLocationsByMaterial={stockLocationsByMaterial}
        records={records}
        t={tItemLists}
        tGlobal={tGlobal}
        currencySymbol={currencySymbol}
      />
    </div>
  );
}
