import DashboardLayout from '@/components/layout/dashboard-layout';
import WorkTasksTable from '@/components/employee/work-tasks-table';
import { verifySession } from '@/lib/auth';

import { hasEmployeePermission } from '@/lib/employee-permissions';
import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import type { InternalTransferDocument, ProductionItem, StockLocationBalance, Warehouse, Employee } from '@/lib/types';

export default async function WorkTasksPage() {
  const { user } = await verifySession();
  if (!user) return null;

  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tDashboard = t.DashboardLayout ?? {};
  const tGlobal = t.Global ?? {};

  const settings = await (await import('@/lib/postgres/data-access')).pgGetSettings();
  const canAccessAdminWorkTasks = hasEmployeePermission(user, settings, 'admin.work-tasks');
  const canAccessEmployeeWorkTasks = hasEmployeePermission(user, settings, 'employee.work-tasks');

  if (!canAccessAdminWorkTasks && !canAccessEmployeeWorkTasks) {
    return (
      <DashboardLayout>
        <div className="text-center">
          <h1 className="text-2xl font-bold">{tGlobal.accessDenied ?? 'Access denied'}</h1>
          <p>{tGlobal.noPermission ?? 'You do not have permission to view this page.'}</p>
        </div>
      </DashboardLayout>
    );
  }

  let warehouses: Warehouse[] = [];
  let employees: Employee[] = [];
  let documents: InternalTransferDocument[] = [];
  let approvalDocuments: InternalTransferDocument[] = [];
  let materials: ProductionItem[] = [];
  let stockLocationsByMaterial: Record<string, StockLocationBalance[]> = {};
  let historicalShelfKeysByMaterial: Record<string, string[]> = {};

  
  const {
  pgGetWarehouses,
  pgGetInternalTransfers,
  pgGetMaterials,
  pgGetInventoryMovements,
  pgGetEmployees,
  } = await import('@/lib/postgres/data-access');
  const [warehousesResult, transfersResult, materialsResult, movementsResult, employeesResult] = await Promise.all([
  pgGetWarehouses({ page: 1, pageSize: 5000 }),
  pgGetInternalTransfers({ page: 1, pageSize: 5000 }),
  pgGetMaterials({ page: 1, pageSize: 5000 }),
  pgGetInventoryMovements({ page: 1, pageSize: 10000 }),
  pgGetEmployees({ page: 1, pageSize: 5000 }),
  ]);

  warehouses = (warehousesResult.items || []) as Warehouse[];
  employees = (employeesResult.items || []) as Employee[];

  const warehouseIds = canAccessAdminWorkTasks
  ? warehouses.map((wh) => wh.id)
  : user.warehouseIds ?? [];
  const allowedIds = new Set(warehouseIds.filter(Boolean));
  const transfers = ((transfersResult.items || []) as InternalTransferDocument[]).map((doc) => ({
  ...doc,
  receiptStatus: doc.receiptStatus ?? 'pending',
  }));

  documents = transfers.filter((doc) => {
  if (doc.status !== 'active') return false;
  if ((doc.receiptStatus ?? 'pending') !== 'pending') return false;
  return doc.items.some((item) => allowedIds.has(item.toWarehouseId));
  });

  approvalDocuments = transfers.filter((doc) => {
  if (doc.status !== 'active') return false;
  return doc.items.some((item) => item.overageStatus === 'pending' && allowedIds.has(item.fromWarehouseId));
  });

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

  const allowedMaterialIds = new Set(materials.map((material) => material.id));
  const balanceMap = ((movementsResult.items || []) as Array<Record<string, unknown>>).reduce<Map<string, number>>((acc, movement) => {
  const materialId = String(movement.materialId || '').trim();
  const warehouseId = String(movement.warehouseId || '').trim();
  const shelfId = String(movement.shelfId || '').trim();
  if (!allowedMaterialIds.has(materialId) || !warehouseId || !shelfId) return acc;

  const netQuantity = Number(movement.quantityIn || 0) - Number(movement.quantityOut || 0);
  if (!Number.isFinite(netQuantity) || netQuantity === 0) return acc;

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

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

  historicalShelfKeysByMaterial = ((movementsResult.items || []) as Array<Record<string, unknown>>).reduce<Record<string, string[]>>((acc, movement) => {
  const materialId = String(movement.materialId || '').trim();
  const warehouseId = String(movement.warehouseId || '').trim();
  const shelfId = String(movement.shelfId || '').trim();
  if (!materialId || !warehouseId || !shelfId) return acc;

  const key = `${warehouseId}||${shelfId}`;
  const existing = acc[materialId] || [];
  if (!existing.includes(key)) {
    existing.push(key);
  }
  acc[materialId] = existing;
  return acc;
  }, {});
  

  return (
    <DashboardLayout>
      <div className="mx-auto grid w-full max-w-6xl gap-2">
        <h1 className="text-3xl font-semibold">{tDashboard?.workTasks ?? 'مهام العمل'}</h1>
        <WorkTasksTable
          employees={employees}
          incomingDocuments={documents}
          approvalDocuments={approvalDocuments}
          materials={materials}
          warehouses={warehouses}
          stockLocationsByMaterial={stockLocationsByMaterial}
          historicalShelfKeysByMaterial={historicalShelfKeysByMaterial}
          userRole={user.role}
          allowedSenderWarehouseIds={canAccessAdminWorkTasks ? warehouses.map((wh) => wh.id) : []}
        />
      </div>
    </DashboardLayout>
  );
}
