/**
 * Sales Invoice Creation Page
 * URL: /admin/sales
 */

import { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';

import { issueActionGuardToken } from '@/lib/action-guard';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import {
  pgGetCustomers,
  pgGetSuppliers,
  pgGetEmployees,
  pgGetMaterials,
  pgGetCampaigns,
  pgGetActiveWarehouses,
  pgGetCurrencies,
  pgGetCustomerPricing,
  pgGetInventoryMovements,
  pgGetSettings,
  pgGetSalesReps,
  pgGetManagedUnits,
} from '@/lib/postgres/data-access';
import SalesInvoiceForm from '@/components/admin/sales/sales-invoice-form';

export const metadata: Metadata = {
  title: 'إنشاء فاتورة مبيعات',
};

export default async function SalesCreatePage() {
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const rawCustomers = ((await pgGetCustomers({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawSuppliers = ((await pgGetSuppliers({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawMaterials = ((await pgGetMaterials({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawCampaigns = (await pgGetCampaigns()) as any[];
  const rawUnits = ((await pgGetManagedUnits({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawEmployees = ((await pgGetEmployees({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawSalesReps = ((await pgGetSalesReps({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawWarehouses = ((await pgGetActiveWarehouses()).items || []) as any[];
  const rawCurrencies = ((await pgGetCurrencies({ page: 1, pageSize: 5000 })).items || []) as any[];
  const rawCustomerPricing = ((await pgGetCustomerPricing({ page: 1, pageSize: 5000 })).items || []) as any[];
  const defaultCurrency = rawCurrencies.find((c: any) => c?.isDefault === true || c?.isDefault === 'true') || rawCurrencies[0];
  const settings = await pgGetSettings();
  if (!hasEmployeePermission(session.user, settings, 'admin.sales')) {
    redirect('/');
  }
  const warehousesEnabled = settings.warehousesEnabled === true || settings.warehousesEnabled === 'true';
  const salesRepsEnabled = settings.salesRepsEnabled === true || settings.salesRepsEnabled === 'true';
  const businessMode = String(settings.businessMode || '').trim();
  const realEstateEnabled = businessMode === 'real-estate' || businessMode === 'hybrid' || settings.realEstateEnabled === true || settings.realEstateEnabled === 'true';
  const isRealEstateOnlyMode = businessMode === 'real-estate' || (!businessMode && realEstateEnabled);
  const effectiveWarehousesEnabled = warehousesEnabled && !isRealEstateOnlyMode;
  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 blockSalesBelowCost = settings.blockSalesBelowCost === true || settings.blockSalesBelowCost === 'true';
  const salesShipmentWorkflowEnabled = settings.salesShipmentWorkflowEnabled === true || settings.salesShipmentWorkflowEnabled === 'true';
  const defaultSalesWarehouseId = String(settings.defaultSalesWarehouseId || '').trim();

  const allowedWarehouseIds = session.user.role === 'admin'
    ? null
    : new Set((session.user.warehouseIds || []).map((warehouseId) => String(warehouseId || '').trim()).filter(Boolean));

  const filteredWarehouses = effectiveWarehousesEnabled
    ? rawWarehouses.filter((wh) => {
        if (!allowedWarehouseIds) return true;
        return allowedWarehouseIds.has(String(wh.id || '').trim());
      })
    : [];

  const defaultWarehouseId = effectiveWarehousesEnabled
    ? (filteredWarehouses.find((wh) => wh.id === defaultSalesWarehouseId)?.id || filteredWarehouses[0]?.id || '')
    : '';

  const allowedWarehouseSet = new Set(filteredWarehouses.map((wh) => String(wh.id || '').trim()).filter(Boolean));
  const rawInventoryMovements = effectiveWarehousesEnabled
    ? (((await pgGetInventoryMovements({ page: 1, pageSize: 5000 })).items || []) as any[])
    : [];
  const movementEntries = effectiveWarehousesEnabled
    ? rawInventoryMovements.map((movement: any) => ({
              materialId: movement.materialId,
              warehouseId: movement.warehouseId,
              shelfId: movement.shelfId,
              quantity: Number(movement.quantityOut || movement.quantityIn || 0),
              direction: Number(movement.quantityOut || 0) > 0 ? 'out' : 'in',
            }))
    : [];
  const stockByMaterialAndLocation = movementEntries.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.quantity || 0);
    if (!materialId || !warehouseId || !shelfId || !Number.isFinite(quantity) || quantity <= 0) return acc;
    if (!allowedWarehouseSet.has(warehouseId)) return acc;
    const key = `${materialId}||${warehouseId}||${shelfId}`;
    const signedQty = movement.direction === 'out' ? -quantity : quantity;
    acc.set(key, (acc.get(key) || 0) + signedQty);
    return acc;
  }, new Map<string, number>());

  const stockLocationsByMaterial = Array.from(stockByMaterialAndLocation.entries()).reduce<Record<string, Array<{ warehouseId: string; shelfId: string; quantity: number }>>>((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({ warehouseId, shelfId, quantity });
    acc[materialId] = list;
    return acc;
  }, {});

  const customers = [
    ...rawCustomers.map((c) => ({
      id: c.id,
      label: c.name,
      description: c.customerNumber,
      allowedDiscount: c.allowedDiscount,
      salesRepId: c.salesRepId,
      category: c.category,
    })),
    ...rawSuppliers
      .filter((s) => !s.inactive)
      .map((s) => ({
        id: `sup_${s.id}`,
        label: s.name,
        description: s.supplierNumber,
        allowedDiscount: undefined,
        salesRepId: undefined,
        category: undefined,
      })),
  ];

  const realEstateProjectById = new Map(realEstateProjects.map((project: any) => [String(project.id || '').trim(), project]));
  const materials = rawMaterials.map((m) => {
    const linkedProject = realEstateProjectById.get(String(m.realEstateProjectId || '').trim());
    const linkedUnit = (linkedProject?.units || []).find((unit: any) => String(unit.id || '').trim() === String(m.realEstateUnitId || '').trim());
    return {
      id: m.id,
      name: m.name,
      itemNumber: m.itemNumber,
      itemSymbolName: m.itemSymbolName,
      barcode: m.barcode,
      alternativeItemIds: Array.isArray(m.alternativeItemIds) ? m.alternativeItemIds : [],
      purchasePrice: m.purchasePrice,
      salePrice: m.salePrice,
      categoryPrices: m.categoryPrices,
      primaryUnit: m.primaryUnit,
      taxRate: m.taxRate,
      realEstateProjectId: String(m.realEstateProjectId || '').trim() || undefined,
      realEstateProjectName: String(linkedProject?.name || '').trim() || undefined,
      realEstateUnitId: String(m.realEstateUnitId || '').trim() || undefined,
      realEstateUnitName: String(linkedUnit?.name || linkedUnit?.unitCode || '').trim() || undefined,
    };
  });

  const warehouses = filteredWarehouses.map((wh) => ({
    id: wh.id,
    name: wh.name,
    shelves: (wh.shelves || []).map((shelf) => ({ id: shelf.id, name: shelf.name })),
  }));
  const salesReps = [
    ...rawSalesReps.map((rep: any) => ({ id: rep.id, name: rep.name })),
    ...rawEmployees
      .filter((employee) => {
        const businessRole = String(employee.businessRole || '').trim().toLowerCase();
        return businessRole === 'مندوب مبيعات' || businessRole === 'sales rep' || businessRole === 'sales-rep';
      })
      .filter((employee) => !rawSalesReps.find((rep: any) => rep.id === employee.id))
      .map((employee) => ({ id: employee.id, name: employee.name })),
  ];

  // Determine if current user is a sales rep and get their rep ID
  const currentUserBusinessRole = String(session.user.businessRole || '').trim().toLowerCase();
  const isCurrentUserSalesRep = currentUserBusinessRole === 'مندوب مبيعات' || currentUserBusinessRole === 'sales rep' || currentUserBusinessRole === 'sales-rep';
  const currentUserSalesRepId = isCurrentUserSalesRep ? session.user.id : '';
  const currencies = rawCurrencies.map((c) => ({
    code: c.code,
    name: c.name,
    symbol: c.symbol,
    exchangeRate: c.exchangeRate,
  }));
  const rawGeneralBanks = await (await import('@/lib/postgres/data-access')).pgGetGeneralBanks();
  const banks = (rawGeneralBanks || []).filter((bank: any) => bank && typeof bank.id === 'string' && bank.isActive !== false);

  const salesActionGuardToken = issueActionGuardToken('sales', session.user.id);

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-3xl font-bold">إنشاء فاتورة مبيعات</h1>
      </div>

      <SalesInvoiceForm
        userId={session.user.id}
        userName={session.user.name}
        customers={customers}
        campaigns={rawCampaigns}
        materials={materials}
        unitDefinitions={rawUnits}
        warehouses={warehouses}
        stockLocationsByMaterial={stockLocationsByMaterial}
        inventoryMovements={rawInventoryMovements}
        customerPricing={rawCustomerPricing}
        warehousesEnabled={effectiveWarehousesEnabled}
        blockSalesBelowCost={blockSalesBelowCost}
        defaultWarehouseId={defaultWarehouseId}
        salesReps={salesReps}
        salesRepsEnabled={salesRepsEnabled}
        currencies={currencies}
        banks={banks}
        defaultCurrencyCode={defaultCurrency?.code}
        defaultTaxMethod={String(settings.defaultTaxMethod || '').trim() as any}
        defaultSalesRepId={currentUserSalesRepId}
        realEstateProjects={realEstateProjects}
        realEstateEnabled={realEstateEnabled}
        actionGuardToken={salesActionGuardToken}
        shipmentWorkflowEnabled={salesShipmentWorkflowEnabled}
      />
    </div>
  );
}
