import PurchaseOrderForm from '@/components/admin/purchase-order-form';
import { verifySession } from '@/lib/auth';

import { getCurrentLocale, getTranslations } from '@/lib/i18n';
import { getCurrencySymbolAsync } from '@/lib/server-currency';
import { issueActionGuardToken } from '@/lib/action-guard';
import { isPurchaseOrderLockActive } from '@/lib/purchase-order-lock';

export default async function EditPurchaseOrderPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tPurchases = t.Purchases ?? {};
  const tGlobal = t.Global ?? {};

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

  let order = undefined;
  let suppliers = [];
  let customers = [];
  let materials = [];
  let purchaseOrders = [];
  let currencies = [];
  let baseCurrency = undefined;
  let exchangeRateSources = [];
  let chartOfAccounts = [];
  let itemGroups = [];
  let categories = [];
  const currencySymbol = await getCurrencySymbolAsync();
  let warehouses = [];
  let settings = ({} as any);
  let incomingChecks = [];
  let banks = [];

  let stockLocationsByMaterial = {};
  let materialShelfHistoryByMaterial: Record<string, string[]> = {};

  
  const {
  pgGetSuppliers,
  pgGetCustomers,
  pgGetMaterials,
  pgGetPurchaseOrders,
  pgGetCurrencies,
  pgGetDefaultCurrency,
  pgGetExchangeRateSources,
  pgGetChartOfAccounts,
  pgGetItemGroups,
  pgGetCustomerCategories,
  pgGetActiveWarehouses,
  pgGetSettings,
  pgGetBanks,
  pgGetChecksReceived,
  pgGetInventoryMovements,
  } = await import('@/lib/postgres/data-access');

  const [
  suppliersResult,
  customersResult,
  materialsResult,
  purchaseOrdersResult,
  currenciesResult,
  baseCurrencyResult,
  exchangeRateSourcesResult,
  chartOfAccountsResult,
  itemGroupsResult,
  categoriesResult,
  warehousesResult,
  settingsResult,
  banksResult,
  checksReceivedResult,
  movementsResult,
  ] = await Promise.all([
  pgGetSuppliers({ page: 1, pageSize: 5000 }),
  pgGetCustomers({ page: 1, pageSize: 5000 }),
  pgGetMaterials({ page: 1, pageSize: 5000 }),
  pgGetPurchaseOrders({ page: 1, pageSize: 5000 }),
  pgGetCurrencies({ page: 1, pageSize: 5000 }),
  pgGetDefaultCurrency(),
  pgGetExchangeRateSources({ page: 1, pageSize: 5000 }),
  pgGetChartOfAccounts({ page: 1, pageSize: 5000 }),
  pgGetItemGroups({ page: 1, pageSize: 5000 }),
  pgGetCustomerCategories({ page: 1, pageSize: 5000 }),
  pgGetActiveWarehouses(),
  pgGetSettings(),
  pgGetBanks({ page: 1, pageSize: 5000 }),
  pgGetChecksReceived({ page: 1, pageSize: 5000 }),
  pgGetInventoryMovements({ page: 1, pageSize: 10000 }),
  ]);

  suppliers = (suppliersResult.items || []) as typeof suppliers;
  customers = (customersResult.items || []) as typeof customers;
  materials = (materialsResult.items || []) as typeof materials;
  purchaseOrders = (purchaseOrdersResult.items || []) as typeof purchaseOrders;
  order = purchaseOrders.find((candidate) => candidate.id === id) || order;
  currencies = (currenciesResult.items || []) as typeof currencies;
  baseCurrency = (baseCurrencyResult as typeof baseCurrency) || baseCurrency;
  exchangeRateSources = (exchangeRateSourcesResult.items || []) as unknown as typeof exchangeRateSources;
  chartOfAccounts = (chartOfAccountsResult.items || []) as typeof chartOfAccounts;
  itemGroups = (itemGroupsResult.items || []) as typeof itemGroups;
  categories = (categoriesResult.items || []) as typeof categories;
  warehouses = (warehousesResult.items || []) as typeof warehouses;
  settings = (settingsResult as typeof settings) || settings;
  banks = (banksResult.items || []) as typeof banks;
  incomingChecks = (checksReceivedResult.items || []) as typeof incomingChecks;

  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 movementRows = ((movementsResult.items || []) as Array<Record<string, unknown>>).filter((movement) => {
  const materialId = String(movement.materialId || '').trim();
  const warehouseId = String(movement.warehouseId || '').trim();
  const shelfId = String(movement.shelfId || '').trim();
  return materialId && warehouseId && shelfId;
  });

  const stockBalanceMap = movementRows.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 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(stockBalanceMap.entries()).reduce<Record<string, any[]>>((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;
  }, {});

  materialShelfHistoryByMaterial = movementRows.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}`;
  if (!acc[materialId]) {
    acc[materialId] = [];
  }
  if (!acc[materialId].includes(key)) {
    acc[materialId].push(key);
  }
  return acc;
  }, {});
  

  if (!order) {
    return (
      <div className="text-center">
        <h1 className="text-xl font-semibold">{tPurchases?.orderNotFound ?? 'الأمر غير موجود'}</h1>
        <p className="text-muted-foreground">{tPurchases?.orderNotFoundHint ?? 'تعذر العثور على أمر الشراء المطلوب.'}</p>
      </div>
    );
  }

  if ((order.postingStatus || 'posted') === 'posted') {
    return (
      <div className="text-center">
        <h1 className="text-xl font-semibold">{tPurchases?.postedOrderEditLockedTitle ?? 'الفاتورة مرحلة'}</h1>
        <p className="text-muted-foreground">{tPurchases?.postedOrderEditLockedDesc ?? 'لا يمكن تعديل الفاتورة بعد الترحيل. استخدم إجراء عكسي أو تسوية.'}</p>
      </div>
    );
  }

  if (isPurchaseOrderLockActive(order) && order.lockedById && order.lockedById !== user.id) {
    return (
      <div className="text-center">
        <h1 className="text-xl font-semibold">{tPurchases?.purchaseOrderLocked ?? 'الفاتورة قيد التعديل'}</h1>
        <p className="text-muted-foreground">
          {(tPurchases?.purchaseOrderLockedBy ?? 'يتم التعديل على الفاتورة من قبل {name}.')
            .replace('{name}', order.lockedByName || order.lockedById || 'مستخدم آخر')}
        </p>
      </div>
    );
  }

  const allowedWarehouses = user.role === 'admin'
    ? warehouses
    : (user.warehouseIds && user.warehouseIds.length > 0)
      ? warehouses.filter((w) => user.warehouseIds?.includes(w.id))
      : warehouses;

  const warehousesEnabled = settings.warehousesEnabled === true || settings.warehousesEnabled === 'true';
  const normalizedUserWarehouseIds = (user.warehouseIds || [])
    .map((warehouseId) => String(warehouseId || '').trim())
    .filter(Boolean);
  const userPreferredWarehouseId = normalizedUserWarehouseIds.find((warehouseId) =>
    allowedWarehouses.some((warehouse) => warehouse.id === warehouseId)
  ) || '';
  const settingsDefaultWarehouseId = warehousesEnabled ? String(settings.defaultPurchaseWarehouseId || '').trim() : '';
  const resolvedDefaultWarehouseId = warehousesEnabled
    ? (userPreferredWarehouseId
      || (allowedWarehouses.some((warehouse) => warehouse.id === settingsDefaultWarehouseId) ? settingsDefaultWarehouseId : ''))
    : '';
  const selectedDefaultWarehouse = allowedWarehouses.find((warehouse) => warehouse.id === resolvedDefaultWarehouseId);
  const selectedDefaultWarehouseShelves = Array.isArray(selectedDefaultWarehouse?.shelves) ? selectedDefaultWarehouse.shelves : [];
  const settingsDefaultShelfId = warehousesEnabled ? String(settings.defaultPurchaseShelfId || '').trim() : '';
  const resolvedDefaultShelfId = warehousesEnabled
    ? ((settingsDefaultShelfId && selectedDefaultWarehouseShelves.some((shelf) => shelf.id === settingsDefaultShelfId))
      ? settingsDefaultShelfId
      : (selectedDefaultWarehouseShelves[0]?.id || ''))
    : '';
  const purchaseWarehouseConfig = {
    enabled: warehousesEnabled,
    defaultWarehouseId: resolvedDefaultWarehouseId,
    defaultShelfId: resolvedDefaultShelfId,
  };
  const defaultTaxMethod = (settings.defaultTaxMethod as 'tax-inclusive' | 'invoice-level' | 'line-level' | 'tax-exempt') || 'tax-inclusive';
  const defaultTaxRate = Number(settings.defaultInvoiceTaxRate) || 0;
  const businessMode = String(settings.businessMode || '').trim();
  const realEstateEnabled = businessMode === 'real-estate' || businessMode === 'hybrid' || settings.realEstateEnabled === true || settings.realEstateEnabled === 'true';
  const realEstateProjectsResult = realEstateEnabled
    ? await (await import('@/lib/actions')).handleGetRealEstateProjects()
    : null;
  const realEstateProjects = realEstateEnabled && realEstateProjectsResult && 'success' in realEstateProjectsResult && realEstateProjectsResult.success
    ? (((realEstateProjectsResult as any).items || []) as any[])
    : []; 

  const purchaseActionGuardToken = issueActionGuardToken('purchase', user.id);

  return (
    <PurchaseOrderForm
      suppliers={suppliers}
      customers={customers}
      materials={materials}
      purchaseOrders={purchaseOrders}
      itemGroups={itemGroups}
      categories={categories}
      t={tPurchases}
      tGlobal={tGlobal}
      currencySymbol={currencySymbol}
      currencies={currencies}
      baseCurrency={baseCurrency}
      exchangeRateSources={exchangeRateSources}
      stockLocationsByMaterial={stockLocationsByMaterial}
      materialShelfHistoryByMaterial={materialShelfHistoryByMaterial}
      warehouses={allowedWarehouses}
      incomingChecks={incomingChecks}
      banks={banks}
      chartOfAccounts={chartOfAccounts}
      realEstateProjects={realEstateProjects}
      realEstateEnabled={realEstateEnabled}
      warehouseConfig={purchaseWarehouseConfig}
      defaultTaxMethod={defaultTaxMethod}
      defaultTaxRate={defaultTaxRate}
      mode="edit"
      existingOrder={order}
      actionGuardToken={purchaseActionGuardToken}
      shipmentWorkflowEnabled={settings.purchaseShipmentWorkflowEnabled === true || settings.purchaseShipmentWorkflowEnabled === 'true'}
      aiInvoiceEntryEnabled={settings.aiInvoiceEntryEnabled === true || settings.aiInvoiceEntryEnabled === 'true'}
      purchasePostingFollowupEnabled={settings.purchasePostingFollowupEnabled === true || settings.purchasePostingFollowupEnabled === 'true'}
    />
  );
}
