/**
 * Sales Edit Page
 * Edit an existing sales invoice (draft only)
 * URL: /admin/sales/edit/[id]
 */

import { Metadata } from 'next';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';

import { issueActionGuardToken } from '@/lib/action-guard';
import { handleGetSalesInvoice } from '@/lib/actions/sales-invoice.actions';
import SalesInvoiceForm from '@/components/admin/sales/sales-invoice-form';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  pgGetCustomers,
  pgGetSuppliers,
  pgGetMaterials,
  pgGetCampaigns,
  pgGetActiveWarehouses,
  pgGetSalesReps,
  pgGetCurrencies,
  pgGetCustomerPricing,
  pgGetInventoryMovements,
  pgGetSettings,
  pgGetManagedUnits,
} from '@/lib/postgres/data-access';

export const metadata: Metadata = {
  title: 'Edit Sales Invoice | Sales Management',
};

interface SalesEditPageProps {
  params: Promise<{
    id: string;
  }>;
}

export default async function SalesEditPage({ params }: SalesEditPageProps) {
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const { id } = await params;
  const result = await handleGetSalesInvoice(id);

  if (!result.success || !result.data) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>تعذر تحميل الفاتورة</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground">الفاتورة غير موجودة أو تم حذفها.</p>
          <Button asChild className="mt-4" variant="outline">
            <Link href="/admin/sales/history">العودة إلى السجل</Link>
          </Button>
        </CardContent>
      </Card>
    );
  }

  const invoice = result.data;

  if (invoice.status !== 'active') {
    return (
      <Card>
        <CardHeader>
          <CardTitle>لا يمكن تعديل هذه الفاتورة</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-muted-foreground">
            فقط الفواتير النشطة يمكن تعديلها. الحالة الحالية: {invoice.status}
          </p>
          <Button asChild variant="outline">
            <Link href={`/admin/sales/view/${invoice.id}`}>عرض الفاتورة</Link>
          </Button>
        </CardContent>
      </Card>
    );
  }

  // Reference data for dropdowns

  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 rawWarehouses = ((await pgGetActiveWarehouses()).items || []) as any[];
  const rawSalesReps = ((await pgGetSalesReps({ page: 1, pageSize: 5000 })).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();
  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((sr) => ({ id: sr.id, name: sr.name }));
  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);

  const initialData = {
    customerId: invoice.customerId,
    secondaryCustomerId: (invoice as any).secondaryCustomerId || '',
    secondaryCoveragePercent: Number((invoice as any).secondaryCoveragePercent || 0),
    date: invoice.date,
    warehouseId: invoice.items.find((item) => String(item.warehouseId || '').trim())?.warehouseId || defaultWarehouseId,
    items: invoice.items.map((item) => ({
      materialId: item.materialId,
      quantity: item.quantity,
      unitPrice: item.unitPrice,
      lineDiscountPercent: item.lineDiscountPercent || 0,
      lineDiscountAmount: item.lineDiscountAmount || 0,
      taxRate: item.taxRate || 0,
      shelfId: item.shelfId,
    })),
    salesRepId: invoice.salesRepId,
    currencyCode: invoice.currencyCode,
    exchangeRate: invoice.exchangeRate,
    rateSource: invoice.rateSource,
    invoiceDiscountPercent: invoice.invoiceDiscountPercent || 0,
    invoiceDiscountAmount: invoice.invoiceDiscountAmount || 0,
    amountReceived: invoice.amountReceived || 0,
    paymentMethods: invoice.paymentMethods || [],
    realEstateProjectId: (invoice as any).realEstateProjectId || '',
    realEstateProjectName: (invoice as any).realEstateProjectName || '',
    realEstateUnitId: (invoice as any).realEstateUnitId || '',
    realEstateUnitName: (invoice as any).realEstateUnitName || '',
    realEstateContractNumber: (invoice as any).realEstateContractNumber || '',
    realEstateContractDate: (invoice as any).realEstateContractDate || '',
    realEstateHandoverDate: (invoice as any).realEstateHandoverDate || '',
    realEstateContractValue: Number((invoice as any).realEstateContractValue || 0),
    realEstateInstallmentMode: ((invoice as any).realEstateInstallmentMode || 'existing') as 'existing' | 'auto',
    realEstateInstallmentCount: Number((invoice as any).realEstateInstallmentCount || 0),
    realEstateFirstDueDate: (invoice as any).realEstateFirstDueDate || '',
    realEstateInstallmentInterval: ((invoice as any).realEstateInstallmentInterval || 'monthly') as 'monthly' | 'quarterly',
    customerNotes: invoice.customerNotes || '',
    internalNotes: invoice.internalNotes || '',
    taxMethod: invoice.taxMethod,
    documentType: (invoice as any).documentType || 'tax_invoice',
    activityLog: Array.isArray((invoice as any).activityLog) ? (invoice as any).activityLog : [],
  };

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-3xl font-bold">تعديل فاتورة المبيعات</h1>
        <p className="text-muted-foreground mt-1">{invoice.invoiceNumber}</p>
      </div>

      <SalesInvoiceForm
        userId={session.user.id}
        userName={session.user.name}
        mode="edit"
        invoiceId={invoice.id}
        initialData={initialData}
        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=""
        realEstateProjects={realEstateProjects}
        realEstateEnabled={realEstateEnabled}
        actionGuardToken={salesActionGuardToken}
        shipmentWorkflowEnabled={salesShipmentWorkflowEnabled}
      />
    </div>
  );

}

