/**
 * Sales Invoice Form
 * Create/edit sales invoices with real data from server
 */

'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useForm, useFieldArray, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter } from 'next/navigation';
import { useToast } from '@/hooks/use-toast';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Trash2, PlusCircle, ChevronsUpDown, ChevronDown, Settings } from 'lucide-react';
import type { Bank, Campaign, GeneralBank, ManagedUnit } from '@/lib/types';
import { computeCampaignLivePreview } from '@/lib/campaign-live-preview';
import { cn, formatDateDDMMYYYY } from '@/lib/utils';

import { PartySelector } from '@/components/invoice-shared/party-selector';
import { CalculationDisplay } from '@/components/invoice-shared/calculation-display';

import {
  handleCreateSalesInvoice,
  handleUpdateSalesInvoice,
  handleGetUnlinkedShipmentsForCustomer,
} from '@/lib/actions/sales-invoice.actions';

// --- Schema ----------------------------------------------------------------
const lineItemSchema = z.object({
  materialId: z.string().optional().default(''),
  name: z.string().optional(),
  realEstateProjectId: z.string().optional(),
  realEstateProjectName: z.string().optional(),
  realEstateUnitId: z.string().optional(),
  realEstateUnitName: z.string().optional(),
  quantity: z.coerce.number().min(0.001, 'الكمية يجب أن تكون أكبر من صفر'),
  unitPrice: z.coerce.number().min(0),
  lineDiscountPercent: z.coerce.number().min(0).max(100).optional(),
  lineDiscountAmount: z.coerce.number().min(0).optional(),
  taxRate: z.coerce.number().min(0).max(100).optional(),
  shelfId: z.string().optional(),
  description: z.string().optional(),
}).superRefine((item, ctx) => {
  const quantity = Number(item.quantity || 0);
  const unitPrice = Number(item.unitPrice || 0);
  const lineDiscountPercent = Number(item.lineDiscountPercent || 0);
  const lineDiscountAmount = Number(item.lineDiscountAmount || 0);
  const taxRate = Number(item.taxRate || 0);
  const hasOptionalText = Boolean(String(item.name || '').trim() || String(item.shelfId || '').trim() || String(item.description || '').trim());

  const isBlankRow = !String(item.materialId || '').trim()
    && !String(item.realEstateProjectId || '').trim()
    && !String(item.realEstateUnitId || '').trim()
    && quantity === 1
    && unitPrice === 0
    && lineDiscountPercent === 0
    && lineDiscountAmount === 0
    && taxRate === 0
    && !hasOptionalText;

  if (isBlankRow) {
    return;
  }

  const hasMaterial = Boolean(String(item.materialId || '').trim());
  const hasRealEstateUnit = Boolean(String(item.realEstateProjectId || '').trim() && String(item.realEstateUnitId || '').trim());

  if (!hasMaterial && !hasRealEstateUnit) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['materialId'],
      message: 'يجب اختيار صنف أو وحدة عقارية.',
    });
  }
});

const paymentCheckSchema = z.object({
  checkNumber: z.string().min(1, 'رقم الشيك مطلوب'),
  bankId: z.string().min(1, 'البنك مطلوب'),
  bankName: z.string().min(1, 'اسم البنك مطلوب'),
  checkDate: z.string().min(1, 'تاريخ الشيك مطلوب'),
  amount: z.coerce.number().min(0.01, 'المبلغ يجب أن يكون أكبر من صفر'),
  currency: z.string().min(1, 'العملة مطلوبة'),
  status: z.enum(['pending', 'cleared', 'rejected', 'returned']).optional(),
  reference: z.string().optional(),
});

const salesInvoiceSchema = z.object({
  customerId: z.string().min(1, 'العميل مطلوب'),
  secondaryCustomerId: z.string().optional(),
  secondaryCoveragePercent: z.coerce.number().min(0).max(100).optional().default(0),
  date: z.string().min(1),
  manualDocNumber: z.string().optional(),
  salesRepId: z.string().optional(),
  warehouseId: z.string().optional(),
  currencyCode: z.string().optional(),
  exchangeRate: z.coerce.number().optional(),
  taxMethod: z.enum(['tax-inclusive', 'invoice-level', 'line-level', 'tax-exempt']).optional(),
  taxExemptionReason: z.string().optional(),
  taxExemptionReference: z.string().optional(),
  invoiceDiscountPercent: z.coerce.number().min(0).max(100).optional(),
  invoiceDiscountAmount: z.coerce.number().min(0).optional(),
  items: z.array(lineItemSchema).min(1, 'أضف مادة واحدة على الأقل'),
  amountReceived: z.coerce.number().min(0).optional(),
  paymentMethodsSelected: z.array(z.enum(['cash', 'check', 'credit'])).min(1, 'اختر طريقة دفع واحدة على الأقل'),
  cashAmount: z.coerce.number().min(0).optional(),
  paymentChecks: z.array(paymentCheckSchema).optional(),
  realEstateProjectId: z.string().optional(),
  realEstateProjectName: z.string().optional(),
  realEstateUnitId: z.string().optional(),
  realEstateUnitName: z.string().optional(),
  realEstateContractNumber: z.string().optional(),
  realEstateContractDate: z.string().optional(),
  realEstateHandoverDate: z.string().optional(),
  realEstateContractValue: z.coerce.number().min(0).optional(),
  realEstateInstallmentMode: z.enum(['existing', 'auto']).optional().default('existing'),
  realEstateInstallmentCount: z.coerce.number().int().min(0).optional().default(0),
  realEstateFirstDueDate: z.string().optional(),
  realEstateInstallmentInterval: z.enum(['monthly', 'quarterly']).optional().default('monthly'),
  customerNotes: z.string().optional(),
  internalNotes: z.string().optional(),
}).superRefine((data, ctx) => {
  const selectedMethods = new Set(data.paymentMethodsSelected || []);

  if (selectedMethods.has('cash') && Number(data.cashAmount || 0) <= 0) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['cashAmount'],
      message: 'أدخل مبلغ النقد.',
    });
  }

  if (selectedMethods.has('check')) {
    if (!Array.isArray(data.paymentChecks) || data.paymentChecks.length === 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['paymentChecks'],
        message: 'أضف شيكاً واحداً على الأقل.',
      });
    }

    if (data.currencyCode) {
      const mismatchIndex = (data.paymentChecks || []).findIndex(
        (check) => String(check.currency || '').trim() && check.currency !== data.currencyCode
      );
      if (mismatchIndex >= 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['paymentChecks', mismatchIndex, 'currency'],
          message: 'يجب أن تكون عملة الشيك مطابقة لعملة الفاتورة.',
        });
      }
    }
  }

  if (data.taxMethod === 'tax-exempt') {
    if (!String(data.taxExemptionReason || '').trim()) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['taxExemptionReason'],
        message: 'سبب الإعفاء الضريبي مطلوب.',
      });
    }
    if (!String(data.taxExemptionReference || '').trim()) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['taxExemptionReference'],
        message: 'مرجع/رقم وثيقة الإعفاء الضريبي مطلوب.',
      });
    }
  }

  const primaryCustomerId = String(data.customerId || '').trim();
  const secondaryCustomerId = String(data.secondaryCustomerId || '').trim();
  const secondaryCoveragePercent = Number(data.secondaryCoveragePercent || 0);

  if (secondaryCustomerId && secondaryCustomerId === primaryCustomerId) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['secondaryCustomerId'],
      message: 'لا يمكن أن يكون العميل الثانوي هو نفسه العميل الرئيسي.',
    });
  }

  if (secondaryCustomerId) {
    if (!Number.isFinite(secondaryCoveragePercent) || secondaryCoveragePercent <= 0 || secondaryCoveragePercent >= 100) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['secondaryCoveragePercent'],
        message: 'نسبة تغطية العميل الثانوي يجب أن تكون أكبر من 0 وأقل من 100.',
      });
    }
  } else if (secondaryCoveragePercent > 0) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['secondaryCustomerId'],
      message: 'اختر العميل الثانوي أولاً قبل إدخال نسبة التغطية.',
    });
  }

  const hasRealEstateContext = Boolean(String(data.realEstateProjectId || '').trim() && String(data.realEstateUnitId || '').trim());
  if (hasRealEstateContext) {
    if (Number(data.realEstateContractValue || 0) <= 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['realEstateContractValue'],
        message: 'يجب إدخال قيمة عقد العقار وأن تكون موجبة.',
      });
    }

    if (data.realEstateInstallmentMode === 'auto') {
      if (Number(data.realEstateInstallmentCount || 0) <= 0) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['realEstateInstallmentCount'],
          message: 'عدد الأقساط مطلوب عند التوليد التلقائي.',
        });
      }
      if (!String(data.realEstateFirstDueDate || '').trim()) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['realEstateFirstDueDate'],
          message: 'تاريخ أول الأقساط مطلوب عند التوليد التلقائي.',
        });
      }
    }
  }
});

type SalesInvoiceFormData = z.infer<typeof salesInvoiceSchema>;
type LineItemData = z.infer<typeof lineItemSchema>;
type PaymentCheckData = z.infer<typeof paymentCheckSchema>;
type PostingType = 'draft' | 'saved' | 'posted';
type NumericLineField = 'quantity' | 'unitPrice' | 'lineDiscountPercent' | 'lineDiscountAmount' | 'taxRate';
type GridColumnKey = 'item' | 'quantity' | 'unitPrice' | 'discountPercent' | 'taxRate' | 'shelf' | 'total';
type UnitDisplayMode = 'description' | 'shortCode' | 'both';

// --- Prop types -------------------------------------------------------------
export interface MaterialOption {
  id: string;
  name: string;
  itemNumber?: string;
  itemSymbolName?: string;
  barcode?: string;
  purchasePrice?: number;
  salePrice: number;
  categoryPrices?: Record<string, number>;
  primaryUnit?: string;
  taxRate?: number;
  realEstateProjectId?: string;
  realEstateProjectName?: string;
  realEstateUnitId?: string;
  realEstateUnitName?: string;
}

export interface RealEstateUnitOption {
  id: string;
  name?: string;
  unitCode?: string;
  floor?: string;
  saleValue?: number;
  actualSaleValue?: number;
  contractDate?: string;
  handoverDate?: string;
  installments?: Array<{ dueDate?: string }>;
  status?: 'planned' | 'available' | 'reserved' | 'sold';
  notes?: string;
  area?: number;
}

export interface RealEstateFloorUnitDetailOption {
  id: string;
  unitLabel?: string;
  area?: number;
  estimatedSaleValue?: number;
  notes?: string;
}

export interface RealEstateFloorDetailOption {
  id: string;
  floorLabel?: string;
  usageType?: string;
  description?: string;
  unitCount?: number;
  unitArea?: number;
  estimatedUnitSaleValue?: number;
  unitDetails?: RealEstateFloorUnitDetailOption[];
  notes?: string;
}

export interface RealEstateProjectOption {
  id: string;
  name: string;
  designSummary?: string;
  floorDetails?: RealEstateFloorDetailOption[];
  units?: RealEstateUnitOption[];
}

type RealEstatePickerUnitOption = RealEstateUnitOption & {
  projectId: string;
  projectName: string;
  linkedMaterial?: MaterialOption;
};

const REAL_ESTATE_UNIT_STATUS_LABELS: Record<string, string> = {
  planned: 'مخطط',
  available: 'متاح',
  reserved: 'محجوز',
  sold: 'مباع',
};

const REAL_ESTATE_USAGE_LABELS: Record<string, string> = {
  warehouse: 'مستودع',
  parking: 'موقف',
  apartments: 'شقق',
  commercial: 'تجاري',
  services: 'خدمات',
  mixed: 'متعدد الاستخدامات',
  other: 'أخرى',
};

export interface SalesInvoiceFormProps {
  userId: string;
  userName: string;
  mode?: 'create' | 'edit';
  invoiceId?: string;
  initialData?: Partial<SalesInvoiceFormData> & { items?: any[] };
  customers: { id: string; label: string; description?: string; allowedDiscount?: number; salesRepId?: string; category?: string }[];
  campaigns?: Campaign[];
  materials: MaterialOption[];
  unitDefinitions?: ManagedUnit[];
  warehouses: { id: string; name: string; shelves: { id: string; name: string }[] }[];
  stockLocationsByMaterial?: Record<string, Array<{ warehouseId: string; shelfId: string; quantity: number }>>;
  inventoryMovements?: any[];
  customerPricing?: any[];
  warehousesEnabled?: boolean;
  blockSalesBelowCost?: boolean;
  defaultWarehouseId?: string;
  salesReps: { id: string; name: string }[];
  salesRepsEnabled?: boolean;
  currencies: { code: string; name: string; symbol?: string; exchangeRate?: number }[];
  realEstateProjects?: RealEstateProjectOption[];
  realEstateEnabled?: boolean;
  banks: Array<Bank | GeneralBank>;
  defaultCurrencyCode?: string;
  defaultTaxMethod?: 'tax-inclusive' | 'invoice-level' | 'line-level' | 'tax-exempt';
  defaultSalesRepId?: string;
  actionGuardToken: string;
  shipmentWorkflowEnabled?: boolean;
}

// --- Helpers -----------------------------------------------------------------
function emptyItem(): LineItemData {
  return { materialId: '', quantity: 1, unitPrice: 0 };
}

function emptyPaymentCheck(currencyCode?: string): PaymentCheckData {
  return {
    checkNumber: '',
    bankId: '',
    bankName: '',
    checkDate: '',
    amount: 0,
    currency: currencyCode || '',
    status: 'pending',
    reference: '',
  };
}

function calcLineNet(item: LineItemData): number {
  const gross = (item.quantity || 0) * (item.unitPrice || 0);
  const discAmt = item.lineDiscountAmount != null
    ? item.lineDiscountAmount
    : gross * ((item.lineDiscountPercent || 0) / 100);
  return Math.max(0, gross - discAmt);
}

function isEffectivelyEmptyLineItem(item?: Partial<LineItemData> | null): boolean {
  if (!item) return true;

  const quantity = Number(item.quantity || 0);
  const unitPrice = Number(item.unitPrice || 0);
  const lineDiscountPercent = Number(item.lineDiscountPercent || 0);
  const lineDiscountAmount = Number(item.lineDiscountAmount || 0);
  const taxRate = Number(item.taxRate || 0);

  const hasMaterial = Boolean(String(item.materialId || '').trim());
  const hasRealEstateUnit = Boolean(String(item.realEstateProjectId || '').trim() && String(item.realEstateUnitId || '').trim());
  const hasOptionalText = Boolean(String(item.name || '').trim() || String(item.shelfId || '').trim() || String(item.description || '').trim());

  return !hasMaterial
    && !hasRealEstateUnit
    && quantity === 1
    && unitPrice === 0
    && lineDiscountPercent === 0
    && lineDiscountAmount === 0
    && taxRate === 0
    && !hasOptionalText;
}

function toEnglishDigits(value: string): string {
  const arabicIndic = '٠١٢٣٤٥٦٧٨٩';
  const easternArabicIndic = '۰۱۲۳۴۵۶۷۸۹';
  return value
    .replace(/[٠-٩]/g, (digit) => String(arabicIndic.indexOf(digit)))
    .replace(/[۰-۹]/g, (digit) => String(easternArabicIndic.indexOf(digit)));
}

function normalizeDecimalInput(value: string): string {
  const english = toEnglishDigits(value);
  const dotDecimal = english.replace(/,/g, '.');
  return dotDecimal.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
}

function formatDecimal(value: number, fractionDigits = 2): string {
  const safe = Number.isFinite(value) ? value : 0;
  return safe.toLocaleString('en-US', {
    minimumFractionDigits: fractionDigits,
    maximumFractionDigits: fractionDigits,
    useGrouping: false,
  });
}

function normalizeComparableLabel(value?: string): string {
  return String(value || '').trim().toLowerCase().replace(/\s+/g, ' ');
}

function hasMeaningfulUnitDetail(detail?: RealEstateFloorUnitDetailOption): boolean {
  return Boolean(
    String(detail?.unitLabel || '').trim()
    || Number(detail?.area || 0) > 0
    || Number(detail?.estimatedSaleValue || 0) > 0
    || String(detail?.notes || '').trim()
  );
}

function getProjectUnitOptions(project?: RealEstateProjectOption): RealEstateUnitOption[] {
  const explicitUnits = Array.isArray(project?.units)
    ? project.units.filter((unit) => unit && typeof unit === 'object' && (String(unit.id || '').trim() || String(unit.name || unit.unitCode || '').trim()))
    : [];
  const floorDetails = Array.isArray(project?.floorDetails) ? project.floorDetails : [];

  const derivedUnits = floorDetails.flatMap((floor, floorIndex) => {
    const floorId = String(floor?.id || `floor-${floorIndex + 1}`).trim() || `floor-${floorIndex + 1}`;
    const floorLabel = String(floor?.floorLabel || `الطابق ${floorIndex + 1}`).trim() || `الطابق ${floorIndex + 1}`;
    const usageKey = String(floor?.usageType || '').trim();
    const usageLabel = REAL_ESTATE_USAGE_LABELS[usageKey] || usageKey || 'أخرى';
    const floorDescription = String(floor?.description || '').trim();
    const floorNotes = String(floor?.notes || '').trim();
    const defaultArea = Math.max(0, Number(floor?.unitArea || 0));
    const defaultSaleValue = Math.max(0, Number(floor?.estimatedUnitSaleValue || 0));
    const unitDetails = (Array.isArray(floor?.unitDetails) ? floor.unitDetails : []).filter((detail) => hasMeaningfulUnitDetail(detail));

    if (unitDetails.length > 0) {
      return unitDetails.map((detail, detailIndex) => {
        const unitLabel = String(detail?.unitLabel || '').trim() || `${usageLabel} ${detailIndex + 1}`;
        const detailNotes = String(detail?.notes || '').trim();
        const notes = [floorDescription, detailNotes].filter(Boolean).join(' � ');
        return {
          id: String(detail?.id || `${floorId}-unit-${detailIndex + 1}`).trim() || `${floorId}-unit-${detailIndex + 1}`,
          unitCode: `${floorId}-U${detailIndex + 1}`,
          name: unitLabel,
          floor: floorLabel,
          area: Math.max(0, Number(detail?.area || defaultArea || 0)),
          saleValue: Math.max(0, Number(detail?.estimatedSaleValue || defaultSaleValue || 0)) || undefined,
          notes: [usageLabel, notes].filter(Boolean).join(' � ') || undefined,
          status: 'available' as const,
        };
      });
    }

    const explicitCount = Math.max(0, Number(floor?.unitCount || 0));
    const generatedCount = explicitCount > 0 ? explicitCount : (usageKey || floorDescription || floorNotes ? 1 : 0);

    return Array.from({ length: generatedCount }, (_, generatedIndex) => {
      const generatedName = generatedCount === 1
        ? (floorDescription || `${usageLabel} - ${floorLabel}`)
        : `${usageLabel} ${generatedIndex + 1}`;
      const generatedNotes = [floorDescription && generatedName !== floorDescription ? floorDescription : '', floorNotes].filter(Boolean).join(' � ');
      return {
        id: `${floorId}-generated-${generatedIndex + 1}`,
        unitCode: `${floorId}-G${generatedIndex + 1}`,
        name: generatedName,
        floor: floorLabel,
        area: defaultArea,
        saleValue: defaultSaleValue > 0 ? defaultSaleValue : undefined,
        notes: [usageLabel, generatedNotes].filter(Boolean).join(' � ') || undefined,
        status: 'available' as const,
      };
    });
  });

  const mergedUnits = [...derivedUnits, ...explicitUnits];
  const uniqueUnits = new Map<string, RealEstateUnitOption>();
  mergedUnits.forEach((unit, index) => {
    const id = String(unit?.id || '').trim();
    const fallbackKey = `${normalizeComparableLabel(unit?.floor)}::${normalizeComparableLabel(unit?.name || unit?.unitCode)}::${index}`;
    uniqueUnits.set(id || fallbackKey, unit);
  });

  return Array.from(uniqueUnits.values());
}

// --- Component ---------------------------------------------------------------
export default function SalesInvoiceForm({
  userId,
  userName,
  mode = 'create',
  invoiceId,
  initialData,
  customers,
  campaigns = [],
  materials,
  unitDefinitions = [],
  warehouses,
  stockLocationsByMaterial = {},
  warehousesEnabled = false,
  blockSalesBelowCost = false,
  defaultWarehouseId,
  salesReps,
  salesRepsEnabled = false,
  currencies,
  banks,
  defaultCurrencyCode,
  defaultTaxMethod,
  defaultSalesRepId,
  realEstateProjects = [],
  realEstateEnabled = false,
  actionGuardToken,
  shipmentWorkflowEnabled = false,
}: SalesInvoiceFormProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [activeTab, setActiveTab] = useState('items');
  const [lineDrafts, setLineDrafts] = useState<Record<string, string>>({});
  const [lineTotalDrafts, setLineTotalDrafts] = useState<Record<number, string>>({});
  const [headerDrafts, setHeaderDrafts] = useState<Record<string, string>>({});
  const [showItemPicker, setShowItemPicker] = useState(false);
  const [columnSettingsOpen, setColumnSettingsOpen] = useState(false);
  const [showLossDialog, setShowLossDialog] = useState(false);
  const [lossWarnings, setLossWarnings] = useState<Array<{ index: number; materialName: string; cost: number; costCurrency: string; unitPrice: number; saleCurrency: string; quantity: number; lossPerUnit: number; lossAmount: number }>>([]);
  const [pendingLossPayload, setPendingLossPayload] = useState<any | null>(null);
  const [pendingPostingPayload, setPendingPostingPayload] = useState<any | null>(null);
  const [showPostingDialog, setShowPostingDialog] = useState(false);
  const [documentType, setDocumentType] = useState<'shipment' | 'tax_invoice'>(
    ((initialData as any)?.documentType as 'shipment' | 'tax_invoice') || 'tax_invoice'
  );
  const [linkedShipmentIds, setLinkedShipmentIds] = useState<string[]>(
    Array.isArray((initialData as any)?.linkedShipmentIds) ? (initialData as any).linkedShipmentIds : []
  );
  type AvailableShipment = {
    id: string;
    invoiceNumber: string;
    date: string;
    grandTotal: number;
    currencyCode?: string;
    items?: {
      materialId?: string;
      quantity: number;
      unitPrice: number;
      lineDiscountPercent?: number;
      lineDiscountAmount?: number;
      taxRate?: number;
      shelfId?: string;
      description?: string;
      name?: string;
      realEstateProjectId?: string;
      realEstateProjectName?: string;
      realEstateUnitId?: string;
      realEstateUnitName?: string;
    }[];
  };
  const [availableShipments, setAvailableShipments] = useState<AvailableShipment[]>([]);
  const [isFetchingShipments, setIsFetchingShipments] = useState(false);
  const [bankOptions, setBankOptions] = useState<Array<Bank | GeneralBank>>(banks || []);
  const [isAddBankDialogOpen, setIsAddBankDialogOpen] = useState(false);
  const [pendingBankRowIndex, setPendingBankRowIndex] = useState<number | null>(null);
  const [isCreatingBank, setIsCreatingBank] = useState(false);
  const [newBankDraft, setNewBankDraft] = useState({ code: '', name: '', nameEn: '', branch: '' });
  const [paymentCheckBankOpenByRow, setPaymentCheckBankOpenByRow] = useState<Record<number, boolean>>({});
  const [paymentCheckBankQueryByRow, setPaymentCheckBankQueryByRow] = useState<Record<number, string>>({});
  const [selectedPostingType, setSelectedPostingType] = useState<PostingType>('saved');
  const [itemPickerQuery, setItemPickerQuery] = useState('');
  const itemPickerInputRef = useRef<HTMLInputElement | null>(null);
  const [showAvailableOnlyInPicker, setShowAvailableOnlyInPicker] = useState(false);
  const [pickerTargetRowIndex, setPickerTargetRowIndex] = useState<number | null>(null);
  const [selectedRealEstateSectionId, setSelectedRealEstateSectionId] = useState('');
  const [isSectionPickerOpen, setIsSectionPickerOpen] = useState(false);
  const [isRtlLayout, setIsRtlLayout] = useState(true);
  const tablePreferencesStorageKey = 'sales-invoice-grid-preferences';
  const defaultColumnWidths = {
    item: 240,
    quantity: 96,
    unitPrice: 120,
    discountPercent: 96,
    taxRate: 96,
    shelf: 130,
    total: 120,
  };
  const minColumnWidths = {
    item: 180,
    quantity: 80,
    unitPrice: 100,
    discountPercent: 80,
    taxRate: 80,
    shelf: 110,
    total: 100,
  };
  const [columnWidths, setColumnWidths] = useState(defaultColumnWidths);
  const [unitDisplayMode, setUnitDisplayMode] = useState<UnitDisplayMode>('description');
  const [resizingColumnKey, setResizingColumnKey] = useState<GridColumnKey | null>(null);
  const resizeStateRef = useRef<{ key: GridColumnKey; startX: number; startWidth: number } | null>(null);
  const paymentCheckCellRefs = useRef<Record<string, HTMLElement | null>>({});
  const autoSyncedContractValueRef = useRef(0);
  const initialPostingStatus = String((initialData as any)?.postingStatus || '').trim().toLowerCase();
  const initialShippingStatus = String((initialData as any)?.shippingStatus || '').trim().toLowerCase();
  const isEditLockedByStatus = mode === 'edit' && (
    initialPostingStatus === 'posted'
    || initialShippingStatus === 'shipped'
    || initialShippingStatus === 'delivered'
  );
  const editLockReason = initialPostingStatus === 'posted'
    ? 'لا يمكن تعديل فاتورة مرحلة. يلزم إجراء عكس/تسوية ثم إنشاء مستند بديل.'
    : 'لا يمكن تعديل فاتورة تم شحنها/تسليمها. قم بإرجاع أو عكس الشحنة أولاً ثم عدّل.';
  const activityLogEntries = Array.isArray((initialData as any)?.activityLog)
    ? (initialData as any).activityLog
    : [];

  const managedUnitByDescription = useMemo(() => {
    const map = new Map<string, ManagedUnit>();
    (unitDefinitions || []).forEach((unit) => {
      const key = normalizeComparableLabel(unit?.description);
      if (key) map.set(key, unit);
    });
    return map;
  }, [unitDefinitions]);

  const formatManagedUnitDisplay = (unitDescription?: string) => {
    const description = String(unitDescription || '').trim();
    if (!description) return '';
    const managedUnit = managedUnitByDescription.get(normalizeComparableLabel(description));
    const shortCode = String(managedUnit?.shortCode || '').trim();
    if (unitDisplayMode === 'description') return description;
    if (unitDisplayMode === 'shortCode') return shortCode || description;
    return shortCode ? `${description} (${shortCode})` : description;
  };

  const initialPaymentMethods = Array.isArray((initialData as any)?.paymentMethods)
    ? (initialData as any).paymentMethods
    : [];
  const legacyPaymentMethod = String((initialData as any)?.paymentMethod || '').trim();
  const initialSelectedPaymentMethods = (() => {
    const fromMethods = Array.from(
      new Set(
        initialPaymentMethods
          .map((method: any) => String(method?.method || '').trim())
          .filter((method: string) => method === 'cash' || method === 'check' || method === 'credit')
      )
    ) as Array<'cash' | 'check' | 'credit'>;

    if (fromMethods.length > 0) return fromMethods;
    if (legacyPaymentMethod === 'cash' || legacyPaymentMethod === 'check' || legacyPaymentMethod === 'credit') {
      return [legacyPaymentMethod as 'cash' | 'check' | 'credit'];
    }
    if (Number(initialData?.amountReceived || 0) > 0) {
      return ['cash'] as Array<'cash' | 'check' | 'credit'>;
    }
    return ['credit'] as Array<'cash' | 'check' | 'credit'>;
  })();
  const initialCashAmount = Number(
    initialPaymentMethods.find((method: any) => String(method?.method || '').trim() === 'cash')?.amount
      ?? (legacyPaymentMethod === 'cash' ? initialData?.amountReceived : 0)
      ?? 0
  );

  const normalizedDefaultTaxMethod: 'tax-inclusive' | 'invoice-level' | 'line-level' | 'tax-exempt' =
    defaultTaxMethod === 'tax-inclusive' || defaultTaxMethod === 'invoice-level' || defaultTaxMethod === 'line-level' || defaultTaxMethod === 'tax-exempt'
      ? defaultTaxMethod
      : 'line-level';

  const form = useForm<SalesInvoiceFormData>({
    resolver: zodResolver(salesInvoiceSchema),
    defaultValues: {
      customerId: initialData?.customerId ?? '',
      secondaryCustomerId: (initialData as any)?.secondaryCustomerId ?? '',
      secondaryCoveragePercent: Number((initialData as any)?.secondaryCoveragePercent ?? 0),
      date: initialData?.date ?? '',
      manualDocNumber: initialData?.manualDocNumber ?? '',
      salesRepId: initialData?.salesRepId ?? (mode !== 'edit' && defaultSalesRepId ? defaultSalesRepId : ''),
      warehouseId: initialData?.warehouseId ?? defaultWarehouseId ?? '',
      currencyCode: initialData?.currencyCode ?? defaultCurrencyCode ?? '',
      exchangeRate: initialData?.exchangeRate ?? 1,
      taxMethod: (initialData?.taxMethod as any) ?? normalizedDefaultTaxMethod,
      taxExemptionReason: initialData?.taxExemptionReason ?? '',
      taxExemptionReference: initialData?.taxExemptionReference ?? '',
      invoiceDiscountPercent: initialData?.invoiceDiscountPercent ?? 0,
      invoiceDiscountAmount: initialData?.invoiceDiscountAmount ?? 0,
      items: initialData?.items?.length
        ? initialData.items.map((it: any) => ({
            materialId: it.materialId ?? '',
            name: it.name ?? '',
            realEstateProjectId: it.realEstateProjectId ?? '',
            realEstateProjectName: it.realEstateProjectName ?? '',
            realEstateUnitId: it.realEstateUnitId ?? '',
            realEstateUnitName: it.realEstateUnitName ?? '',
            quantity: it.quantity ?? 1,
            unitPrice: it.unitPrice ?? 0,
            lineDiscountPercent: it.lineDiscountPercent ?? 0,
            lineDiscountAmount: it.lineDiscountAmount ?? 0,
            taxRate: it.taxRate ?? 0,
            shelfId: it.shelfId ?? '',
            description: it.description ?? '',
          }))
        : [emptyItem()],
      amountReceived: initialData?.amountReceived ?? 0,
      paymentMethodsSelected: initialSelectedPaymentMethods,
      cashAmount: initialCashAmount,
      paymentChecks: Array.isArray((initialData as any)?.paymentChecks) && (initialData as any).paymentChecks.length > 0
        ? (initialData as any).paymentChecks
        : Array.isArray((initialData as any)?.paymentMethods)
          ? (initialData as any).paymentMethods
              .filter((method: any) => method?.method === 'check')
              .map((method: any) => ({
                checkNumber: method.checkNumber ?? '',
                bankId: method.bankId ?? '',
                bankName: method.bankName ?? '',
                checkDate: method.checkDate ?? '',
                amount: Number(method.amount || 0),
                currency: method.currency ?? initialData?.currencyCode ?? defaultCurrencyCode ?? '',
                status: method.status ?? 'pending',
                reference: method.reference ?? '',
              }))
          : [],
      realEstateProjectId: (initialData as any)?.realEstateProjectId ?? '',
      realEstateProjectName: (initialData as any)?.realEstateProjectName ?? '',
      realEstateUnitId: (initialData as any)?.realEstateUnitId ?? '',
      realEstateUnitName: (initialData as any)?.realEstateUnitName ?? '',
      realEstateContractNumber: (initialData as any)?.realEstateContractNumber ?? '',
      realEstateContractDate: (initialData as any)?.realEstateContractDate ?? (initialData?.date ?? ''),
      realEstateHandoverDate: (initialData as any)?.realEstateHandoverDate ?? '',
      realEstateContractValue: Number((initialData as any)?.realEstateContractValue ?? 0),
      realEstateInstallmentMode: ((initialData as any)?.realEstateInstallmentMode ?? 'existing') as 'existing' | 'auto',
      realEstateInstallmentCount: Number((initialData as any)?.realEstateInstallmentCount ?? 0),
      realEstateFirstDueDate: (initialData as any)?.realEstateFirstDueDate ?? '',
      realEstateInstallmentInterval: ((initialData as any)?.realEstateInstallmentInterval ?? 'monthly') as 'monthly' | 'quarterly',
      customerNotes: initialData?.customerNotes ?? '',
      internalNotes: initialData?.internalNotes ?? '',
    },
  });

  const { fields, append, remove, move } = useFieldArray({ control: form.control, name: 'items' });
  const {
    fields: paymentCheckFields,
    append: appendPaymentCheck,
    remove: removePaymentCheck,
  } = useFieldArray({ control: form.control, name: 'paymentChecks' });
  const [draggingRowIndex, setDraggingRowIndex] = useState<number | null>(null);
  const watchedItems = useWatch({ control: form.control, name: 'items' }) || [];
  const paymentChecks = useWatch({ control: form.control, name: 'paymentChecks' }) || [];
  const selectedPaymentMethods = useWatch({ control: form.control, name: 'paymentMethodsSelected' }) || [];
  const cashAmount = useWatch({ control: form.control, name: 'cashAmount' }) ?? 0;
  const watchedTaxMethod = useWatch({ control: form.control, name: 'taxMethod' }) ?? 'line-level';
  const watchedSecondaryCustomerId = useWatch({ control: form.control, name: 'secondaryCustomerId' }) ?? '';
  const watchedSecondaryCoveragePercent = useWatch({ control: form.control, name: 'secondaryCoveragePercent' }) ?? 0;
  const watchedCurrencyCode = useWatch({ control: form.control, name: 'currencyCode' }) ?? defaultCurrencyCode ?? '';
  const watchedExchangeRate = useWatch({ control: form.control, name: 'exchangeRate' }) ?? 1;
  const watchedWarehouseId = useWatch({ control: form.control, name: 'warehouseId' }) ?? '';
  const watchedRealEstateProjectId = useWatch({ control: form.control, name: 'realEstateProjectId' }) ?? '';
  const watchedRealEstateUnitId = useWatch({ control: form.control, name: 'realEstateUnitId' }) ?? '';
  const watchedRealEstateContractValue = useWatch({ control: form.control, name: 'realEstateContractValue' }) ?? 0;
  const numericWatchedRealEstateContractValue = Number(normalizeDecimalInput(String(watchedRealEstateContractValue ?? 0)) || '0');
  const watchedRealEstateInstallmentMode = useWatch({ control: form.control, name: 'realEstateInstallmentMode' }) ?? 'existing';
  const watchedCustomerId = useWatch({ control: form.control, name: 'customerId' }) ?? '';
  const invoiceDiscountPercent = form.watch('invoiceDiscountPercent') ?? 0;
  const invoiceDiscountAmount = form.watch('invoiceDiscountAmount') ?? 0;
  const normalizedSecondaryCoveragePercent = String(watchedSecondaryCustomerId || '').trim()
    ? Math.max(0, Math.min(100, Number(watchedSecondaryCoveragePercent || 0)))
    : 0;
  const primaryCoveragePercent = Math.max(0, Number((100 - normalizedSecondaryCoveragePercent).toFixed(2)));

  // Fetch unlinked shipments for this customer whenever we switch to tax_invoice mode or customer changes
  useEffect(() => {
    if (!shipmentWorkflowEnabled || documentType !== 'tax_invoice' || !watchedCustomerId) {
      setAvailableShipments([]);
      setLinkedShipmentIds([]);
      return;
    }
    let cancelled = false;
    setIsFetchingShipments(true);
    handleGetUnlinkedShipmentsForCustomer(watchedCustomerId).then((res) => {
      if (cancelled) return;
      setAvailableShipments(res.success ? (res.data || []) : []);
    }).finally(() => {
      if (!cancelled) setIsFetchingShipments(false);
    });
    return () => { cancelled = true; };
  }, [shipmentWorkflowEnabled, documentType, watchedCustomerId]);

  const selectedCustomerScopeTag = useMemo(() => {
    const customer = customers.find((entry) => String(entry.id || '').trim() === String(watchedCustomerId || '').trim());
    return String(customer?.category || 'general').trim().toLowerCase();
  }, [customers, watchedCustomerId]);

  const campaignPreview = useMemo(() => {
    return computeCampaignLivePreview({
      lines: (watchedItems || []).map((item, index) => {
        const quantity = Math.max(0, Number(item?.quantity || 0));
        const unitPrice = Math.max(0, Number(item?.unitPrice || 0));
        const lineSubtotal = quantity * unitPrice;
        const discountFromAmount = Number(item?.lineDiscountAmount || 0);
        const discountFromPercent = lineSubtotal * (Math.max(0, Number(item?.lineDiscountPercent || 0)) / 100);
        const currentDiscount = Math.min(lineSubtotal, Math.max(discountFromAmount, discountFromPercent));

        return {
          lineKey: String(index),
          materialId: String(item?.materialId || '').trim(),
          quantity,
          unitPrice,
          currentDiscount,
        };
      }),
      campaigns,
      customerCategory: selectedCustomerScopeTag,
      atIso: new Date().toISOString(),
      forPos: false,
      isReturn: false,
    });
  }, [watchedItems, campaigns, selectedCustomerScopeTag]);

  // Totals
  const getEffectiveLineNet = (item: LineItemData, index: number) => {
    const previewDiscount = Number(campaignPreview.discountByLineKey[String(index)] || 0);
    const draft = lineTotalDrafts[index];
    if (draft !== undefined && String(draft).trim() !== '') {
      const parsedDraft = Number(normalizeDecimalInput(draft));
      if (Number.isFinite(parsedDraft)) {
        return Math.max(0, parsedDraft - previewDiscount);
      }
    }
    return Math.max(0, calcLineNet(item) - previewDiscount);
  };

  const subTotal = (watchedItems || []).reduce((sum, item, index) => sum + getEffectiveLineNet(item, index), 0);
  const campaignPreviewTotal = Number(campaignPreview.totalCampaignDiscount || 0);
  const invDisc = invoiceDiscountAmount > 0
    ? invoiceDiscountAmount
    : subTotal * (invoiceDiscountPercent / 100);
  const afterInvDisc = Math.max(0, subTotal - invDisc);
  const taxTotal = (watchedItems || []).reduce((sum, item, index) => {
    return sum + getEffectiveLineNet(item, index) * ((item.taxRate || 0) / 100);
  }, 0);
  const grandTotal = afterInvDisc + taxTotal;
  const isCashSelected = selectedPaymentMethods.includes('cash');
  const isCheckSelected = selectedPaymentMethods.includes('check');
  const isCreditSelected = selectedPaymentMethods.includes('credit');
  const paymentChecksTotal = paymentChecks.reduce((sum, check) => sum + Number(check?.amount || 0), 0);
  const immediateCollected = (isCashSelected ? Number(cashAmount || 0) : 0) + (isCheckSelected ? paymentChecksTotal : 0);
  const creditAmount = isCreditSelected ? Math.max(0, grandTotal - immediateCollected) : 0;
  const amountReceived = immediateCollected;
  const amountDue = grandTotal - amountReceived;

  const materialById = useMemo(() => new Map((materials || []).map((material) => [String(material.id || '').trim(), material])), [materials]);
  const realEstateProjectsById = useMemo(
    () => new Map((realEstateProjects || []).map((project) => [String(project.id || '').trim(), project])),
    [realEstateProjects]
  );

  const detectedRealEstateLinks = useMemo(() => {
    const refs = new Map<string, {
      projectId: string;
      projectName?: string;
      unitId: string;
      unitName?: string;
      project?: any;
      unit?: any;
    }>();

    (watchedItems || []).forEach((item) => {
      const materialId = String(item?.materialId || '').trim();
      const material = materialId ? materialById.get(materialId) : undefined;
      const projectId = String(item?.realEstateProjectId || material?.realEstateProjectId || '').trim();
      const unitId = String(item?.realEstateUnitId || material?.realEstateUnitId || '').trim();
      if (!projectId || !unitId) return;
      const project = realEstateProjectsById.get(projectId);
      const unit = getProjectUnitOptions(project).find((entry) => String(entry?.id || '').trim() === unitId);
      refs.set(`${projectId}::${unitId}`, {
        projectId,
        projectName: String(item?.realEstateProjectName || material?.realEstateProjectName || project?.name || '').trim() || undefined,
        unitId,
        unitName: String(item?.realEstateUnitName || material?.realEstateUnitName || unit?.name || unit?.unitCode || '').trim() || undefined,
        project,
        unit,
      });
    });

    return Array.from(refs.values());
  }, [watchedItems, materialById, realEstateProjectsById]);

  const primaryRealEstateLink = detectedRealEstateLinks[0];
  const hasMixedRealEstateLinks = detectedRealEstateLinks.length > 1;
  const realEstateMaterials = useMemo(
    () =>
      (materials || []).filter((material) => {
        const projectId = String(material.realEstateProjectId || '').trim();
        const unitId = String(material.realEstateUnitId || '').trim();
        return projectId && unitId;
      }),
    [materials]
  );
  const realEstateMaterialByPair = useMemo(
    () =>
      new Map(
        realEstateMaterials.map((material) => [
          `${String(material.realEstateProjectId || '').trim()}::${String(material.realEstateUnitId || '').trim()}`,
          material,
        ])
      ),
    [realEstateMaterials]
  );
  const selectedRealEstateProject = useMemo(() => {
    const projectId = String(watchedRealEstateProjectId || primaryRealEstateLink?.projectId || '').trim();
    return realEstateProjectsById.get(projectId);
  }, [watchedRealEstateProjectId, primaryRealEstateLink, realEstateProjectsById]);
  const selectedProjectUnits = useMemo(() => {
    const projectId = String(watchedRealEstateProjectId || primaryRealEstateLink?.projectId || '').trim();
    if (!projectId) return [];
    const project = realEstateProjectsById.get(projectId);

    return getProjectUnitOptions(project).filter((unit) => {
      const unitId = String(unit?.id || '').trim();
      if (!unitId) return false;
      const status = String((unit as any)?.status || '').trim().toLowerCase();
      return status !== 'sold' || unitId === String(watchedRealEstateUnitId || '').trim();
    });
  }, [watchedRealEstateProjectId, watchedRealEstateUnitId, primaryRealEstateLink, realEstateProjectsById]);
  const selectedRealEstateUnit = useMemo(() => {
    const unitId = String(watchedRealEstateUnitId || primaryRealEstateLink?.unitId || '').trim();
    return selectedProjectUnits.find((entry) => String(entry?.id || '').trim() === unitId)
      || getProjectUnitOptions(selectedRealEstateProject).find((entry) => String(entry?.id || '').trim() === unitId);
  }, [watchedRealEstateUnitId, primaryRealEstateLink, selectedProjectUnits, selectedRealEstateProject]);
  const matchedRealEstateFloorDetail = useMemo(() => {
    const floorLabel = normalizeComparableLabel(selectedRealEstateUnit?.floor);
    const floorDetails = selectedRealEstateProject?.floorDetails || [];
    if (!floorLabel) return undefined;

    return floorDetails.find((floor) => {
      const currentLabel = normalizeComparableLabel(floor?.floorLabel);
      return currentLabel === floorLabel || currentLabel.includes(floorLabel) || floorLabel.includes(currentLabel);
    });
  }, [selectedRealEstateProject, selectedRealEstateUnit]);
  const selectedRealEstateFloorDetail = useMemo(() => {
    const floorDetails = selectedRealEstateProject?.floorDetails || [];
    const explicitSection = floorDetails.find((floor) => String(floor?.id || '').trim() === String(selectedRealEstateSectionId || '').trim());
    return explicitSection || matchedRealEstateFloorDetail;
  }, [selectedRealEstateProject, selectedRealEstateSectionId, matchedRealEstateFloorDetail]);
  const selectedRealEstateEngineeringUnitDetail = useMemo(() => {
    const unitKeys = [selectedRealEstateUnit?.name, selectedRealEstateUnit?.unitCode]
      .map((value) => normalizeComparableLabel(value))
      .filter(Boolean);
    if (unitKeys.length === 0) return undefined;

    const unitDetails = selectedRealEstateFloorDetail?.unitDetails || [];
    return unitDetails.find((detail) => {
      const currentLabel = normalizeComparableLabel(detail?.unitLabel);
      return currentLabel && unitKeys.some((key) => key === currentLabel || key.includes(currentLabel) || currentLabel.includes(key));
    });
  }, [selectedRealEstateFloorDetail, selectedRealEstateUnit]);
  const selectedRealEstateUsageLabel = useMemo(() => {
    const usageKey = String(selectedRealEstateFloorDetail?.usageType || '').trim();
    return REAL_ESTATE_USAGE_LABELS[usageKey] || usageKey || '';
  }, [selectedRealEstateFloorDetail]);
  const realEstateSectionCards = useMemo(() => {
    const floorDetails = selectedRealEstateProject?.floorDetails || [];
    const projectUnits = getProjectUnitOptions(selectedRealEstateProject);

    return floorDetails.map((floor, index) => {
      const floorLabel = String(floor?.floorLabel || `الطابق ${index + 1}`).trim();
      const normalizedFloorLabel = normalizeComparableLabel(floorLabel);
      const relatedUnits = projectUnits.filter((unit) => {
        const currentFloorLabel = normalizeComparableLabel(unit?.floor);
        return normalizedFloorLabel && (currentFloorLabel === normalizedFloorLabel || currentFloorLabel.includes(normalizedFloorLabel) || normalizedFloorLabel.includes(currentFloorLabel));
      });

      const derivedUnitCount = relatedUnits.length > 0
        ? relatedUnits.length
        : Math.max(0, Number(floor?.unitCount || (floor?.unitDetails || []).length || 0));
      const derivedArea = Number(
        floor?.unitArea
        || (floor?.unitDetails && floor.unitDetails.length > 0
          ? floor.unitDetails.reduce((sum, detail) => sum + Number(detail?.area || 0), 0) / floor.unitDetails.length
          : 0)
        || 0
      );
      const usageKey = String(floor?.usageType || '').trim();
      const usageLabel = REAL_ESTATE_USAGE_LABELS[usageKey] || usageKey || 'أخرى';

      return {
        id: String(floor?.id || `floor-${index + 1}`),
        floorLabel,
        usageLabel,
        description: String(floor?.description || '').trim(),
        notes: String(floor?.notes || '').trim(),
        unitCount: derivedUnitCount,
        areaLabel: derivedArea > 0
          ? `${derivedUnitCount > 1 ? 'مساحة إجمالية' : 'مساحة الوحدة'}: ${formatDecimal(derivedArea, 2)} م²`
          : '',
      };
    });
  }, [selectedRealEstateProject]);
  const selectedRealEstateDisplayLabel = useMemo(() => {
    const floorLabel = String(selectedRealEstateFloorDetail?.floorLabel || selectedRealEstateUnit?.floor || '').trim();
    const unitLabel = String(
      selectedRealEstateEngineeringUnitDetail?.unitLabel
      || selectedRealEstateUnit?.name
      || selectedRealEstateUnit?.unitCode
      || primaryRealEstateLink?.unitName
      || ''
    ).trim();
    if (floorLabel && unitLabel) return `${floorLabel} / ${unitLabel}`;
    if (floorLabel) return `${floorLabel}${selectedRealEstateUsageLabel ? ` / ${selectedRealEstateUsageLabel}` : ''}`;
    return unitLabel;
  }, [selectedRealEstateFloorDetail, selectedRealEstateUnit, selectedRealEstateEngineeringUnitDetail, primaryRealEstateLink, selectedRealEstateUsageLabel]);
  const requiresEngineeringSectionSelection = realEstateEnabled && realEstateSectionCards.length > 0;
  const selectedRealEstateMaterial = useMemo(() => {
    const projectId = String(watchedRealEstateProjectId || primaryRealEstateLink?.projectId || '').trim();
    const unitId = String(watchedRealEstateUnitId || primaryRealEstateLink?.unitId || '').trim();
    if (!projectId || !unitId) return undefined;
    return realEstateMaterialByPair.get(`${projectId}::${unitId}`);
  }, [watchedRealEstateProjectId, watchedRealEstateUnitId, primaryRealEstateLink, realEstateMaterialByPair]);
  const hasResolvedRealEstateSelection = Boolean(
    (String(watchedRealEstateProjectId || '').trim() && String(watchedRealEstateUnitId || '').trim())
    || detectedRealEstateLinks.length > 0
  );
  const isRealEstateSaleMode = realEstateEnabled && hasResolvedRealEstateSelection;
  const hasUnlinkedItemsInRealEstateMode = useMemo(() => {
    if (!realEstateEnabled || !isRealEstateSaleMode) return false;
    return (watchedItems || []).some((item) => {
      const materialId = String(item?.materialId || '').trim();
      const material = materialId ? materialById.get(materialId) : undefined;
      const projectId = String(item?.realEstateProjectId || material?.realEstateProjectId || '').trim();
      const unitId = String(item?.realEstateUnitId || material?.realEstateUnitId || '').trim();
      return !projectId || !unitId;
    });
  }, [realEstateEnabled, isRealEstateSaleMode, watchedItems, materialById]);
  const hasExplicitRealEstateContractValue = Number.isFinite(numericWatchedRealEstateContractValue) && numericWatchedRealEstateContractValue > 0;
  const realEstateContractValuePreview = Math.max(
    0,
    hasExplicitRealEstateContractValue
      ? numericWatchedRealEstateContractValue
      : Number(grandTotal || selectedRealEstateUnit?.actualSaleValue || selectedRealEstateUnit?.saleValue || 0)
  );
  const realEstateDeferredAmountPreview = Math.max(0, realEstateContractValuePreview - amountReceived);
  const existingInstallmentCount = Array.isArray(selectedRealEstateUnit?.installments) ? selectedRealEstateUnit.installments.length : 0;

  const filteredPickerUnits = useMemo(() => {
    if (!realEstateEnabled) return [] as RealEstatePickerUnitOption[];

    const projectId = String(watchedRealEstateProjectId || '').trim();
    if (!projectId) return [] as RealEstatePickerUnitOption[];

    const project = realEstateProjectsById.get(projectId);
    const selectedSectionFloorLabel = normalizeComparableLabel(selectedRealEstateFloorDetail?.floorLabel);
    const baseUnits = (selectedProjectUnits || [])
      .filter((unit) => {
        if (!selectedSectionFloorLabel) return true;
        const currentFloorLabel = normalizeComparableLabel(unit?.floor);
        return currentFloorLabel === selectedSectionFloorLabel
          || currentFloorLabel.includes(selectedSectionFloorLabel)
          || selectedSectionFloorLabel.includes(currentFloorLabel);
      })
      .map((unit) => {
        const unitId = String(unit?.id || '').trim();
        return {
          ...unit,
          projectId,
          projectName: String(project?.name || '').trim(),
          linkedMaterial: unitId ? realEstateMaterialByPair.get(`${projectId}::${unitId}`) : undefined,
        } as RealEstatePickerUnitOption;
      });

    const q = itemPickerQuery.trim().toLowerCase();
    if (!q) return baseUnits;

    return baseUnits.filter((unit) => {
      const haystack = [
        unit.name,
        unit.unitCode,
        unit.floor,
        unit.projectName,
        unit.notes,
        REAL_ESTATE_UNIT_STATUS_LABELS[String(unit.status || '').trim().toLowerCase()] || unit.status,
        unit.linkedMaterial?.name,
        unit.linkedMaterial?.itemNumber,
      ].filter(Boolean).join(' ').toLowerCase();
      return haystack.includes(q);
    });
  }, [realEstateEnabled, watchedRealEstateProjectId, realEstateProjectsById, selectedProjectUnits, realEstateMaterialByPair, itemPickerQuery, selectedRealEstateFloorDetail]);

  const filteredPickerMaterials = useMemo(() => {
    if (realEstateEnabled) return [] as MaterialOption[];

    const q = itemPickerQuery.trim().toLowerCase();
    let rows = materials;

    if (showAvailableOnlyInPicker) {
      rows = rows.filter((material) => {
        const locations = stockLocationsByMaterial[String(material.id || '').trim()] || [];
        const availableQty = locations
          .filter((location) => !watchedWarehouseId || String(location.warehouseId || '').trim() === watchedWarehouseId)
          .reduce((sum, location) => sum + Number(location.quantity || 0), 0);
        return availableQty > 0;
      });
    }

    if (!q) return rows;

    return rows.filter((material) => {
      const haystack = [
        material.name,
        material.itemNumber,
        material.itemSymbolName,
        material.barcode,
      ].filter(Boolean).join(' ').toLowerCase();
      return haystack.includes(q);
    });
  }, [materials, realEstateEnabled, itemPickerQuery, showAvailableOnlyInPicker, stockLocationsByMaterial, watchedWarehouseId]);

  const getMaterialPrimaryUnitLabel = (material?: MaterialOption | null) => {
    return formatManagedUnitDisplay(String(material?.primaryUnit || '').trim());
  };

  const paymentCheckVisibleColumnCount = mode === 'edit' ? 8 : 7;

  const setPaymentCheckCellRef = (rowIndex: number, colIndex: number, node: HTMLElement | null) => {
    paymentCheckCellRefs.current[`${rowIndex}:${colIndex}`] = node;
  };

  const focusPaymentCheckCell = (rowIndex: number, colIndex: number) => {
    const target = paymentCheckCellRefs.current[`${rowIndex}:${colIndex}`];
    if (!target) return;
    target.focus();
    if (target instanceof HTMLInputElement) {
      target.select();
    }
  };

  const handlePaymentCheckGridKeyDown = (
    event: React.KeyboardEvent<HTMLElement>,
    rowIndex: number,
    colIndex: number,
  ) => {
    const key = event.key;
    if (key !== 'Enter' && key !== 'ArrowRight' && key !== 'ArrowLeft' && key !== 'ArrowDown' && key !== 'ArrowUp') {
      return;
    }

    const target = event.target as HTMLElement;
    const expanded = target.getAttribute('aria-expanded') === 'true';
    if (expanded && (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Enter')) {
      return;
    }

    event.preventDefault();

    if (key === 'Enter' || key === 'ArrowRight') {
      const nextCol = (colIndex + 1) % paymentCheckVisibleColumnCount;
      const nextRow = nextCol === 0 ? Math.min(rowIndex + 1, paymentCheckFields.length - 1) : rowIndex;
      focusPaymentCheckCell(nextRow, nextCol);
      return;
    }

    if (key === 'ArrowLeft') {
      const prevCol = colIndex === 0 ? paymentCheckVisibleColumnCount - 1 : colIndex - 1;
      const prevRow = colIndex === 0 ? Math.max(0, rowIndex - 1) : rowIndex;
      focusPaymentCheckCell(prevRow, prevCol);
      return;
    }

    if (key === 'ArrowDown') {
      const nextRow = Math.min(rowIndex + 1, paymentCheckFields.length - 1);
      focusPaymentCheckCell(nextRow, colIndex);
      return;
    }

    const prevRow = Math.max(0, rowIndex - 1);
    focusPaymentCheckCell(prevRow, colIndex);
  };

  useEffect(() => {
    setBankOptions(banks || []);
  }, [banks]);

  useEffect(() => {
    if (!realEstateEnabled) {
      if (selectedRealEstateSectionId) setSelectedRealEstateSectionId('');
      return;
    }

    const projectId = String(watchedRealEstateProjectId || '').trim();
    const availableSectionIds = new Set((selectedRealEstateProject?.floorDetails || []).map((floor) => String(floor?.id || '').trim()).filter(Boolean));
    if (!projectId) {
      if (selectedRealEstateSectionId) setSelectedRealEstateSectionId('');
      return;
    }

    if (String(matchedRealEstateFloorDetail?.id || '').trim()) {
      const matchedId = String(matchedRealEstateFloorDetail?.id || '').trim();
      if (selectedRealEstateSectionId !== matchedId) {
        setSelectedRealEstateSectionId(matchedId);
      }
      return;
    }

    if (selectedRealEstateSectionId && !availableSectionIds.has(selectedRealEstateSectionId)) {
      setSelectedRealEstateSectionId('');
    }
  }, [realEstateEnabled, watchedRealEstateProjectId, selectedRealEstateProject, matchedRealEstateFloorDetail, selectedRealEstateSectionId]);

  useEffect(() => {
    if (!realEstateEnabled || !primaryRealEstateLink) return;

    const currentProjectId = String(form.getValues('realEstateProjectId') || '').trim();
    const currentUnitId = String(form.getValues('realEstateUnitId') || '').trim();
    const fallbackContractDate = String(primaryRealEstateLink.unit?.contractDate || form.getValues('date') || '').slice(0, 10);
    const fallbackHandoverDate = String(primaryRealEstateLink.unit?.handoverDate || '').slice(0, 10);
    const fallbackContractValue = Math.max(0, Number(primaryRealEstateLink.unit?.actualSaleValue || primaryRealEstateLink.unit?.saleValue || 0));
    const existingInstallments = Array.isArray(primaryRealEstateLink.unit?.installments) ? primaryRealEstateLink.unit.installments : [];

    if (currentProjectId !== primaryRealEstateLink.projectId) {
      form.setValue('realEstateProjectId', primaryRealEstateLink.projectId, { shouldDirty: false, shouldValidate: false });
      form.setValue('realEstateProjectName', primaryRealEstateLink.projectName || '', { shouldDirty: false, shouldValidate: false });
    }
    if (currentUnitId !== primaryRealEstateLink.unitId) {
      form.setValue('realEstateUnitId', primaryRealEstateLink.unitId, { shouldDirty: false, shouldValidate: false });
      form.setValue('realEstateUnitName', primaryRealEstateLink.unitName || '', { shouldDirty: false, shouldValidate: false });
    }
    if (!String(form.getValues('realEstateContractDate') || '').trim() && fallbackContractDate) {
      form.setValue('realEstateContractDate', fallbackContractDate, { shouldDirty: false, shouldValidate: false });
    }
    if (!String(form.getValues('realEstateHandoverDate') || '').trim() && fallbackHandoverDate) {
      form.setValue('realEstateHandoverDate', fallbackHandoverDate, { shouldDirty: false, shouldValidate: false });
    }
    if (Number(form.getValues('realEstateContractValue') || 0) <= 0 && fallbackContractValue > 0) {
      form.setValue('realEstateContractValue', fallbackContractValue, { shouldDirty: false, shouldValidate: false });
    }
    if (Number(form.getValues('realEstateInstallmentCount') || 0) <= 0 && existingInstallments.length > 0) {
      form.setValue('realEstateInstallmentCount', existingInstallments.length, { shouldDirty: false, shouldValidate: false });
    }
    if (!String(form.getValues('realEstateFirstDueDate') || '').trim() && existingInstallments[0]?.dueDate) {
      form.setValue('realEstateFirstDueDate', String(existingInstallments[0].dueDate || '').slice(0, 10), { shouldDirty: false, shouldValidate: false });
    }
  }, [realEstateEnabled, primaryRealEstateLink, form]);

  useEffect(() => {
    if (!realEstateEnabled || !hasResolvedRealEstateSelection) return;

    const currentValue = Number(normalizeDecimalInput(String(form.getValues('realEstateContractValue') ?? 0)) || '0');
    const nextSuggestedValue = Math.max(0, Number(grandTotal || 0));
    const canAutoSync = currentValue <= 0 || Math.abs(currentValue - autoSyncedContractValueRef.current) < 0.01;

    if (canAutoSync && Math.abs(currentValue - nextSuggestedValue) > 0.01) {
      form.setValue('realEstateContractValue', nextSuggestedValue, { shouldDirty: true, shouldValidate: false });
      autoSyncedContractValueRef.current = nextSuggestedValue;
    }
  }, [realEstateEnabled, hasResolvedRealEstateSelection, grandTotal, form]);

  useEffect(() => {
    if (!realEstateEnabled) return;

    const projectId = String(watchedRealEstateProjectId || '').trim();
    const unitId = String(watchedRealEstateUnitId || '').trim();
    const project = projectId ? realEstateProjectsById.get(projectId) : undefined;
    const unit = unitId ? (project?.units || []).find((entry) => String(entry?.id || '').trim() === unitId) : undefined;

    const nextProjectName = String(project?.name || '').trim();
    if (String(form.getValues('realEstateProjectName') || '').trim() !== nextProjectName) {
      form.setValue('realEstateProjectName', nextProjectName, { shouldDirty: false, shouldValidate: false });
    }

    const nextUnitName = String(unit?.name || unit?.unitCode || '').trim();
    if (String(form.getValues('realEstateUnitName') || '').trim() !== nextUnitName) {
      form.setValue('realEstateUnitName', nextUnitName, { shouldDirty: false, shouldValidate: false });
    }

    if (!projectId || !unitId) return;

    const linkedMaterial = realEstateMaterialByPair.get(`${projectId}::${unitId}`);
    const firstItem = watchedItems?.[0];
    if (!firstItem) return;

    const firstProjectId = String(firstItem.realEstateProjectId || '').trim();
    const firstProjectName = String(firstItem.realEstateProjectName || '').trim();
    const firstUnitId = String(firstItem.realEstateUnitId || '').trim();
    const firstUnitName = String(firstItem.realEstateUnitName || '').trim();
    const selectionChanged = firstProjectId !== projectId || firstUnitId !== unitId;

    if (firstProjectId !== projectId) {
      updateItem(0, 'realEstateProjectId', projectId);
    }
    if (firstProjectName !== nextProjectName) {
      updateItem(0, 'realEstateProjectName', nextProjectName);
    }
    if (firstUnitId !== unitId) {
      updateItem(0, 'realEstateUnitId', unitId);
    }
    if (firstUnitName !== nextUnitName) {
      updateItem(0, 'realEstateUnitName', nextUnitName);
    }

    if (!linkedMaterial) {
      const fallbackUnitName = nextUnitName || 'وحدة عقارية';
      const fallbackUnitPrice = Number(unit?.actualSaleValue || unit?.saleValue || 0);

      if (String(firstItem.materialId || '').trim()) {
        updateItem(0, 'materialId', '');
      }
      if (String(firstItem.name || '').trim() !== fallbackUnitName) {
        updateItem(0, 'name', fallbackUnitName);
      }
      if (Number(firstItem.quantity || 0) !== 1) {
        updateItem(0, 'quantity', 1);
      }
      if (selectionChanged && Number(firstItem.lineDiscountPercent || 0) !== 0) {
        updateItem(0, 'lineDiscountPercent', 0);
      }
      if (selectionChanged && Number(firstItem.lineDiscountAmount || 0) !== 0) {
        updateItem(0, 'lineDiscountAmount', 0);
      }
      if ((selectionChanged || Number(firstItem.unitPrice || 0) <= 0) && Number(firstItem.unitPrice || 0) !== fallbackUnitPrice) {
        updateItem(0, 'unitPrice', fallbackUnitPrice);
      }
      if (String(firstItem.shelfId || '').trim()) {
        updateItem(0, 'shelfId', '');
      }
      return;
    }

    const linkedMaterialId = String(linkedMaterial.id || '').trim();
    const linkedPrice = Number(linkedMaterial.salePrice || unit?.actualSaleValue || unit?.saleValue || 0);

    if (String(firstItem.materialId || '').trim() !== linkedMaterialId) {
      updateItem(0, 'materialId', linkedMaterial.id);
    }
    if (String(firstItem.name || '').trim() !== String(linkedMaterial.name || '').trim()) {
      updateItem(0, 'name', linkedMaterial.name);
    }
    if (Number(firstItem.quantity || 0) !== 1) {
      updateItem(0, 'quantity', 1);
    }
    if (selectionChanged && Number(firstItem.lineDiscountPercent || 0) !== 0) {
      updateItem(0, 'lineDiscountPercent', 0);
    }
    if (selectionChanged && Number(firstItem.lineDiscountAmount || 0) !== 0) {
      updateItem(0, 'lineDiscountAmount', 0);
    }
    if ((selectionChanged || Number(firstItem.unitPrice || 0) <= 0) && Number(firstItem.unitPrice || 0) !== linkedPrice) {
      updateItem(0, 'unitPrice', linkedPrice);
    }
    if (linkedMaterial.taxRate != null && (selectionChanged || Number(firstItem.taxRate || 0) <= 0) && Number(firstItem.taxRate || 0) !== Number(linkedMaterial.taxRate)) {
      updateItem(0, 'taxRate', linkedMaterial.taxRate);
    }
  }, [realEstateEnabled, watchedRealEstateProjectId, watchedRealEstateUnitId, realEstateProjectsById, realEstateMaterialByPair, watchedItems, form]);

  const resetNewBankDraft = () => {
    setNewBankDraft({ code: '', name: '', nameEn: '', branch: '' });
  };

  const handleCreateGeneralBank = async () => {
    const payload = {
      code: newBankDraft.code.trim(),
      name: newBankDraft.name.trim(),
      nameEn: newBankDraft.nameEn.trim() || newBankDraft.name.trim(),
      branch: newBankDraft.branch.trim() || undefined,
      isActive: true,
    };

    if (!payload.code || !payload.name) {
      toast({ title: 'حقول مطلوبة', description: 'يرجى ملء كود البنك واسمه على الأقل.', variant: 'destructive' });
      return;
    }

    setIsCreatingBank(true);
    try {
      const response = await fetch('/api/general-banks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const result = await response.json().catch(() => null);
      if (!response.ok) {
        throw new Error(String(result?.error || 'Failed to create bank'));
      }

      const createdBank = result as GeneralBank;
      setBankOptions((prev) => [...prev, createdBank]);
      if (pendingBankRowIndex !== null) {
        form.setValue(`paymentChecks.${pendingBankRowIndex}.bankId`, createdBank.id, { shouldDirty: true, shouldValidate: true });
        form.setValue(`paymentChecks.${pendingBankRowIndex}.bankName`, String(createdBank.name || createdBank.nameEn || createdBank.code || ''), { shouldDirty: true, shouldValidate: true });
      }
      setIsAddBankDialogOpen(false);
      setPendingBankRowIndex(null);
      resetNewBankDraft();
      toast({ title: 'تمّ الإضافة', description: 'تمّ إضافة البنك بنجاح إلى قائمة البنوك.' });
    } catch (error) {
      toast({
        title: 'فشل إنشاء البنك',
        description: error instanceof Error ? error.message : 'حدث خطأ أثناء الإضافة.',
        variant: 'destructive',
      });
    } finally {
      setIsCreatingBank(false);
    }
  };

  const shelfNameById = useMemo(() => {
    const map = new Map<string, string>();
    for (const warehouse of warehouses) {
      for (const shelf of warehouse.shelves || []) {
        map.set(`${warehouse.id}||${shelf.id}`, shelf.name);
      }
    }
    return map;
  }, [warehouses]);

  const stockShelfOptionsByRow = useMemo(() => {
    const out: Record<number, Array<{ id: string; name: string; quantity: number }>> = {};
    for (let index = 0; index < watchedItems.length; index += 1) {
      const item = watchedItems[index];
      const materialId = String(item?.materialId || '').trim();
      if (!materialId || !watchedWarehouseId) {
        out[index] = [];
        continue;
      }
      const locations = stockLocationsByMaterial[materialId] || [];
      const filtered = locations
        .filter((location) => String(location.warehouseId || '').trim() === watchedWarehouseId && Number(location.quantity || 0) > 0)
        .map((location) => ({
          id: String(location.shelfId || '').trim(),
          name: shelfNameById.get(`${watchedWarehouseId}||${String(location.shelfId || '').trim()}`) || String(location.shelfId || '').trim(),
          quantity: Number(location.quantity || 0),
        }))
        .filter((entry) => entry.id);

      const dedupMap = new Map<string, { id: string; name: string; quantity: number }>();
      filtered.forEach((entry) => {
        const existing = dedupMap.get(entry.id);
        if (!existing) {
          dedupMap.set(entry.id, entry);
          return;
        }
        dedupMap.set(entry.id, { ...existing, quantity: existing.quantity + entry.quantity });
      });

      out[index] = Array.from(dedupMap.values());
    }
    return out;
  }, [watchedItems, watchedWarehouseId, stockLocationsByMaterial, shelfNameById]);

  const hasMultipleShelvesByRow = useMemo(() => {
    const out: Record<number, boolean> = {};
    Object.entries(stockShelfOptionsByRow).forEach(([index, options]) => {
      out[Number(index)] = options.length > 1;
    });
    return out;
  }, [stockShelfOptionsByRow]);

  const editableColumns = useMemo(() => {
    let cursor = 0;
    const map: {
      item: number;
      quantity: number;
      unitPrice: number;
      discountPercent: number;
      taxRate: number;
      shelf?: number;
      total: number;
      count: number;
    } = {
      item: cursor++,
      quantity: cursor++,
      unitPrice: cursor++,
      discountPercent: cursor++,
      taxRate: cursor++,
      total: 0,
      count: 0,
    };

    if (warehousesEnabled && warehouses.length > 0) {
      map.shelf = cursor++;
    }

    map.total = cursor++;
    map.count = cursor;
    return map;
  }, [warehousesEnabled, warehouses.length]);

  useEffect(() => {
    const dir = document.documentElement.getAttribute('dir');
    const lang = document.documentElement.lang || '';
    setIsRtlLayout(dir === 'rtl' || lang.startsWith('ar'));
  }, []);

  useEffect(() => {
    try {
      const rawPreferences = window.localStorage.getItem(tablePreferencesStorageKey);
      if (!rawPreferences) return;
      const parsed = JSON.parse(rawPreferences) as {
        columnWidths?: Partial<typeof columnWidths>;
        showUnitShortCode?: boolean;
        unitDisplayMode?: UnitDisplayMode;
      };
      if (parsed.columnWidths) {
        setColumnWidths((prev) => ({
          item: Math.max(minColumnWidths.item, Number(parsed.columnWidths?.item ?? prev.item)),
          quantity: Math.max(minColumnWidths.quantity, Number(parsed.columnWidths?.quantity ?? prev.quantity)),
          unitPrice: Math.max(minColumnWidths.unitPrice, Number(parsed.columnWidths?.unitPrice ?? prev.unitPrice)),
          discountPercent: Math.max(minColumnWidths.discountPercent, Number(parsed.columnWidths?.discountPercent ?? prev.discountPercent)),
          taxRate: Math.max(minColumnWidths.taxRate, Number(parsed.columnWidths?.taxRate ?? prev.taxRate)),
          shelf: Math.max(minColumnWidths.shelf, Number(parsed.columnWidths?.shelf ?? prev.shelf)),
          total: Math.max(minColumnWidths.total, Number(parsed.columnWidths?.total ?? prev.total)),
        }));
      }
      const mode = parsed.unitDisplayMode;
      if (mode === 'description' || mode === 'shortCode' || mode === 'both') {
        setUnitDisplayMode(mode);
      } else {
        // Backward compatibility with the old boolean preference.
        setUnitDisplayMode(parsed.showUnitShortCode === true ? 'both' : 'description');
      }
    } catch {
      // Ignore invalid local preferences.
    }
  }, []);

  useEffect(() => {
    if (!warehousesEnabled) return;
    if (!watchedWarehouseId) {
      watchedItems.forEach((_, index) => updateItem(index, 'shelfId', ''));
      return;
    }
    watchedItems.forEach((item, index) => {
      const materialId = String(item?.materialId || '').trim();
      const shelfId = String(item?.shelfId || '');
      if (!materialId) {
        if (shelfId) updateItem(index, 'shelfId', '');
        return;
      }
      const options = stockShelfOptionsByRow[index] || [];
      const validShelfIds = new Set(options.map((shelf) => shelf.id));
      if (options.length === 1) {
        const onlyShelfId = options[0].id;
        if (onlyShelfId && shelfId !== onlyShelfId) {
          updateItem(index, 'shelfId', onlyShelfId);
        }
        return;
      }
      if (shelfId && !validShelfIds.has(shelfId)) {
        updateItem(index, 'shelfId', '');
      }
    });
  }, [warehousesEnabled, watchedWarehouseId, watchedItems, stockShelfOptionsByRow]);

  useEffect(() => {
    window.localStorage.setItem(
      tablePreferencesStorageKey,
      JSON.stringify({
        columnWidths,
        unitDisplayMode,
      })
    );
  }, [columnWidths, unitDisplayMode]);

  useEffect(() => {
    if (form.getValues('date')) return;
    const today = new Date().toISOString().split('T')[0];
    form.setValue('date', today, { shouldDirty: false, shouldValidate: false });
  }, [form]);

  useEffect(() => {
    const handleMouseMove = (event: MouseEvent) => {
      if (!resizeStateRef.current) return;
      const { key, startX, startWidth } = resizeStateRef.current;
      const delta = event.clientX - startX;
      const minWidth = minColumnWidths[key];
      setColumnWidths((prev) => ({
        ...prev,
        [key]: Math.max(minWidth, startWidth + delta),
      }));
    };

    const stopResize = () => {
      resizeStateRef.current = null;
      setResizingColumnKey(null);
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    };

    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', stopResize);

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', stopResize);
    };
  }, []);

  useEffect(() => {
    if (!isCheckSelected) return;
    const checks = form.getValues('paymentChecks') || [];
    checks.forEach((check, index) => {
      if (!check?.currency && watchedCurrencyCode) {
        form.setValue(`paymentChecks.${index}.currency`, watchedCurrencyCode, { shouldDirty: true, shouldValidate: false });
      }
      if (!check?.status) {
        form.setValue(`paymentChecks.${index}.status`, 'pending', { shouldDirty: true, shouldValidate: false });
      }
    });
  }, [isCheckSelected, watchedCurrencyCode, form, paymentCheckFields.length]);

  useEffect(() => {
    if (String(watchedSecondaryCustomerId || '').trim()) return;
    if (Number(form.getValues('secondaryCoveragePercent') || 0) === 0) return;
    form.setValue('secondaryCoveragePercent', 0, { shouldDirty: true, shouldValidate: true });
  }, [watchedSecondaryCustomerId, form]);

  useEffect(() => {
    form.setValue('amountReceived', immediateCollected, { shouldDirty: true, shouldValidate: false });
  }, [immediateCollected, form]);

  useEffect(() => {
    if (watchedTaxMethod !== 'tax-exempt') {
      form.setValue('taxExemptionReason', '', { shouldDirty: false, shouldValidate: false });
      form.setValue('taxExemptionReference', '', { shouldDirty: false, shouldValidate: false });
    }
  }, [watchedTaxMethod, form]);

  useEffect(() => {
    if (!isCheckSelected) return;
    if (paymentCheckFields.length > 0) return;
    appendPaymentCheck(emptyPaymentCheck(watchedCurrencyCode));
  }, [isCheckSelected, paymentCheckFields.length, appendPaymentCheck, watchedCurrencyCode]);

  useEffect(() => {
    if (isCheckSelected) return;
    if ((form.getValues('paymentChecks') || []).length === 0) return;
    form.setValue('paymentChecks', [], { shouldDirty: false, shouldValidate: false });
  }, [isCheckSelected, form, watchedCurrencyCode]);

  useEffect(() => {
    if (isCashSelected) return;
    if (Number(form.getValues('cashAmount') || 0) === 0) return;
    form.setValue('cashAmount', 0, { shouldDirty: true, shouldValidate: false });
  }, [isCashSelected, form]);

  // Helpers for updating a single field of a line item
  function updateItem<K extends keyof LineItemData>(index: number, key: K, value: LineItemData[K]) {
    const path = `items.${index}.${key}` as const;
    const currentValue = form.getValues(path as any) as LineItemData[K];
    if (Object.is(currentValue, value)) return;
    form.setValue(path as any, value, { shouldValidate: false });
  }

  function getDraftKey(index: number, field: NumericLineField): string {
    return `${index}:${field}`;
  }

  function getLineDisplayValue(index: number, field: NumericLineField, value: number | undefined, fractionDigits = 2): string {
    const key = getDraftKey(index, field);
    const draft = lineDrafts[key];
    if (draft !== undefined) return draft;
    return formatDecimal(Number(value || 0), fractionDigits);
  }

  function setLineDraft(index: number, field: NumericLineField, raw: string) {
    const key = getDraftKey(index, field);
    const normalized = normalizeDecimalInput(raw);
    setLineDrafts((prev) => ({ ...prev, [key]: normalized }));
  }

  function commitLineNumber(
    index: number,
    field: NumericLineField,
    raw: string,
    options?: { min?: number; max?: number; fallback?: number }
  ) {
    const parsed = Number(normalizeDecimalInput(raw));
    const fallback = options?.fallback ?? 0;
    let nextValue = Number.isFinite(parsed) ? parsed : fallback;
    if (typeof options?.min === 'number') nextValue = Math.max(options.min, nextValue);
    if (typeof options?.max === 'number') nextValue = Math.min(options.max, nextValue);

    updateItem(index, field as any, nextValue as any);

    const key = getDraftKey(index, field);
    setLineDrafts((prev) => {
      if (!(key in prev)) return prev;
      const next = { ...prev };
      delete next[key];
      return next;
    });
  }

  function getLineTotalDisplayValue(index: number, computedTotal: number): string {
    const draft = lineTotalDrafts[index];
    if (draft !== undefined) return draft;
    return formatDecimal(computedTotal, 2);
  }

  function setLineTotalDraft(index: number, raw: string) {
    const normalized = normalizeDecimalInput(raw);
    setLineTotalDrafts((prev) => ({ ...prev, [index]: normalized }));
  }

  function commitLineTotal(index: number, raw: string) {
    const parsedTotal = Number(normalizeDecimalInput(raw));
    const nextTotal = Number.isFinite(parsedTotal) ? Math.max(0, parsedTotal) : 0;
    const item = watchedItems?.[index];
    if (!item) return;

    const quantity = Math.max(0.001, Number(item.quantity || 0));
    let gross = nextTotal;

    if (item.lineDiscountAmount != null && Number(item.lineDiscountAmount || 0) > 0) {
      gross = nextTotal + Number(item.lineDiscountAmount || 0);
    } else if (Number(item.lineDiscountPercent || 0) > 0) {
      const factor = 1 - Number(item.lineDiscountPercent || 0) / 100;
      gross = factor > 0 ? nextTotal / factor : nextTotal;
    }

    const unitPrice = gross / quantity;
    updateItem(index, 'unitPrice', Number.isFinite(unitPrice) ? unitPrice : 0);

    setLineTotalDrafts((prev) => {
      if (!(index in prev)) return prev;
      const next = { ...prev };
      delete next[index];
      return next;
    });
  }

  function getHeaderDisplayValue(key: string, value: number | undefined, fractionDigits = 2): string {
    const draft = headerDrafts[key];
    if (draft !== undefined) return draft;
    return formatDecimal(Number(value || 0), fractionDigits);
  }

  function setHeaderDraft(key: string, raw: string) {
    const normalized = normalizeDecimalInput(raw);
    setHeaderDrafts((prev) => ({ ...prev, [key]: normalized }));
  }

  function commitHeaderNumber(
    key: 'invoiceDiscountPercent' | 'invoiceDiscountAmount' | 'amountReceived' | 'cashAmount' | 'realEstateContractValue',
    raw: string,
    options?: { min?: number; max?: number; fallback?: number }
  ) {
    const parsed = Number(normalizeDecimalInput(raw));
    const fallback = options?.fallback ?? 0;
    let next = Number.isFinite(parsed) ? parsed : fallback;
    if (typeof options?.min === 'number') next = Math.max(options.min, next);
    if (typeof options?.max === 'number') next = Math.min(options.max, next);

    form.setValue(key, next, { shouldDirty: true, shouldValidate: false });

    setHeaderDrafts((prev) => {
      if (!(key in prev)) return prev;
      const out = { ...prev };
      delete out[key];
      return out;
    });
  }

  function openPickerForRow(rowIndex: number) {
    setPickerTargetRowIndex(rowIndex);
    setItemPickerQuery('');
    if (itemPickerInputRef.current) {
      itemPickerInputRef.current.value = '';
    }
    setShowItemPicker(true);
  }

  function handleAddMaterialFromPicker(material: MaterialOption) {
    if (pickerTargetRowIndex === null) return;
    updateItem(pickerTargetRowIndex, 'materialId', material.id);
    updateItem(pickerTargetRowIndex, 'name', material.name);
    updateItem(pickerTargetRowIndex, 'unitPrice', material.salePrice ?? 0);
    if (realEstateEnabled) {
      updateItem(pickerTargetRowIndex, 'quantity', 1);
    }
    if (material.taxRate != null) {
      updateItem(pickerTargetRowIndex, 'taxRate', material.taxRate);
    }

    const projectId = String(material.realEstateProjectId || '').trim();
    const unitId = String(material.realEstateUnitId || '').trim();
    const project = projectId ? realEstateProjectsById.get(projectId) : undefined;
    const projectName = String(material.realEstateProjectName || project?.name || '').trim();
    const unitName = String(material.realEstateUnitName || '').trim();

    updateItem(pickerTargetRowIndex, 'realEstateProjectId', projectId);
    updateItem(pickerTargetRowIndex, 'realEstateProjectName', projectName);
    updateItem(pickerTargetRowIndex, 'realEstateUnitId', unitId);
    updateItem(pickerTargetRowIndex, 'realEstateUnitName', unitName);

    if (projectId) {
      form.setValue('realEstateProjectId', projectId, { shouldDirty: true, shouldValidate: false });
      form.setValue('realEstateProjectName', projectName, { shouldDirty: true, shouldValidate: false });
    }
    if (unitId) {
      form.setValue('realEstateUnitId', unitId, { shouldDirty: true, shouldValidate: false });
      form.setValue('realEstateUnitName', unitName, { shouldDirty: true, shouldValidate: false });
    }

    if (warehousesEnabled && watchedWarehouseId) {
      const locations = stockLocationsByMaterial[material.id] || [];
      const stockShelfIds = Array.from(
        new Set(
          locations
            .filter((location) => String(location.warehouseId || '').trim() === watchedWarehouseId && Number(location.quantity || 0) > 0)
            .map((location) => String(location.shelfId || '').trim())
            .filter(Boolean)
        )
      );
      const targetShelfId = stockShelfIds[0] || '';
      updateItem(pickerTargetRowIndex, 'shelfId', targetShelfId);
    }

    setShowItemPicker(false);
    setPickerTargetRowIndex(null);
    setItemPickerQuery('');
    if (itemPickerInputRef.current) {
      itemPickerInputRef.current.value = '';
    }
  }

  function handleAddRealEstateUnitFromPicker(unit: RealEstatePickerUnitOption) {
    if (pickerTargetRowIndex === null) return;

    const projectId = String(unit.projectId || watchedRealEstateProjectId || '').trim();
    const project = realEstateProjectsById.get(projectId);
    const projectName = String(unit.projectName || project?.name || '').trim();
    const unitId = String(unit.id || '').trim();
    const unitName = String(unit.name || unit.unitCode || '').trim();
    const linkedMaterial = unit.linkedMaterial || realEstateMaterialByPair.get(`${projectId}::${unitId}`);
    const suggestedPrice = Math.max(0, Number(linkedMaterial?.salePrice ?? unit.actualSaleValue ?? unit.saleValue ?? 0));

    form.setValue('realEstateProjectId', projectId, { shouldDirty: true, shouldValidate: false });
    form.setValue('realEstateProjectName', projectName, { shouldDirty: true, shouldValidate: false });
    form.setValue('realEstateUnitId', unitId, { shouldDirty: true, shouldValidate: false });
    form.setValue('realEstateUnitName', unitName, { shouldDirty: true, shouldValidate: false });

    updateItem(pickerTargetRowIndex, 'realEstateProjectId', projectId);
    updateItem(pickerTargetRowIndex, 'realEstateProjectName', projectName);
    updateItem(pickerTargetRowIndex, 'realEstateUnitId', unitId);
    updateItem(pickerTargetRowIndex, 'realEstateUnitName', unitName);
    updateItem(pickerTargetRowIndex, 'quantity', 1);
    updateItem(pickerTargetRowIndex, 'lineDiscountPercent', 0);
    updateItem(pickerTargetRowIndex, 'lineDiscountAmount', 0);
    updateItem(pickerTargetRowIndex, 'unitPrice', suggestedPrice);

    if (linkedMaterial) {
      updateItem(pickerTargetRowIndex, 'materialId', linkedMaterial.id);
      updateItem(pickerTargetRowIndex, 'name', linkedMaterial.name);
      if (linkedMaterial.taxRate != null) {
        updateItem(pickerTargetRowIndex, 'taxRate', linkedMaterial.taxRate);
      }

      if (warehousesEnabled && watchedWarehouseId) {
        const locations = stockLocationsByMaterial[linkedMaterial.id] || [];
        const stockShelfIds = Array.from(
          new Set(
            locations
              .filter((location) => String(location.warehouseId || '').trim() === watchedWarehouseId && Number(location.quantity || 0) > 0)
              .map((location) => String(location.shelfId || '').trim())
              .filter(Boolean)
          )
        );
        const targetShelfId = stockShelfIds[0] || '';
        updateItem(pickerTargetRowIndex, 'shelfId', targetShelfId);
      }
    } else {
      updateItem(pickerTargetRowIndex, 'materialId', '');
      updateItem(pickerTargetRowIndex, 'name', unitName || 'وحدة عقارية');
      updateItem(pickerTargetRowIndex, 'shelfId', '');
    }

    setShowItemPicker(false);
    setPickerTargetRowIndex(null);
    setItemPickerQuery('');
    if (itemPickerInputRef.current) {
      itemPickerInputRef.current.value = '';
    }
  }

  function startColumnResize(key: GridColumnKey) {
    return (event: React.MouseEvent<HTMLDivElement>) => {
      event.preventDefault();
      event.stopPropagation();
      setResizingColumnKey(key);
      resizeStateRef.current = {
        key,
        startX: event.clientX,
        startWidth: columnWidths[key],
      };
      document.body.style.cursor = 'col-resize';
      document.body.style.userSelect = 'none';
    };
  }

  function renderResizeHandle(key: GridColumnKey) {
    return (
      <div
        className={`absolute inset-y-0 -end-1 z-10 flex w-3 cursor-col-resize items-center justify-center bg-transparent ${resizingColumnKey === key ? 'bg-emerald-100/80' : ''}`}
        onMouseDown={startColumnResize(key)}
      >
        <span
          className={`h-full w-px bg-border/80 transition-all ${resizingColumnKey === key ? 'w-[2px] bg-emerald-500' : 'group-hover:bg-emerald-300'}`}
        />
      </div>
    );
  }

  function focusCell(rowIndex: number, colIndex: number) {
    const target = document.querySelector<HTMLElement>(`[data-cell="${rowIndex}-${colIndex}"]`);
    if (target) target.focus();
  }

  function selectAllOnFocus(event: React.FocusEvent<HTMLInputElement>) {
    requestAnimationFrame(() => {
      event.target.select();
    });
  }

  function ensureSelectOnMouseDown(event: React.MouseEvent<HTMLInputElement>) {
    const input = event.target as HTMLInputElement;
    if (document.activeElement !== input) {
      event.preventDefault();
      input.focus();
      input.select();
    }
  }

  function moveGridRow(fromIndex: number, toIndex: number) {
    if (fromIndex < 0 || fromIndex >= fields.length) return;
    const boundedTarget = Math.max(0, Math.min(toIndex, fields.length - 1));
    if (boundedTarget === fromIndex) return;
    move(fromIndex, boundedTarget);
  }

  function appendEmptyRow() {
    if (realEstateEnabled && fields.length >= 1) return;
    append(emptyItem());
  }

  function handleGridKeyDown(event: React.KeyboardEvent<HTMLElement>, rowIndex: number, colIndex: number) {
    const isMoveUpShortcut = (event.altKey || event.ctrlKey) && (event.key === '-' || event.code === 'NumpadSubtract');
    const isMoveDownShortcut = (event.altKey || event.ctrlKey) && (event.key === '+' || event.code === 'NumpadAdd' || (event.key === '=' && event.shiftKey));

    if (isMoveUpShortcut || isMoveDownShortcut) {
      event.preventDefault();
      const targetRow = isMoveUpShortcut ? rowIndex - 1 : rowIndex + 1;
      moveGridRow(rowIndex, targetRow);
      const boundedRow = Math.max(0, Math.min(targetRow, fields.length - 1));
      setTimeout(() => focusCell(boundedRow, Math.max(0, Math.min(colIndex, editableColumns.count - 1))), 0);
      return;
    }

    if (!['Enter', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return;
    if (event.key === 'ArrowDown' && (event.altKey || event.metaKey)) return;

    event.preventDefault();

    let nextRow = rowIndex;
    let nextCol = colIndex;

    if (event.key === 'Tab') {
      nextCol += event.shiftKey ? -1 : 1;
    } else if (event.key === 'Enter') {
      nextCol += 1;
    } else if (event.key === 'ArrowUp') {
      nextRow -= 1;
    } else if (event.key === 'ArrowDown') {
      nextRow += 1;
    } else if (event.key === 'ArrowRight') {
      nextCol += isRtlLayout ? -1 : 1;
    } else if (event.key === 'ArrowLeft') {
      nextCol += isRtlLayout ? 1 : -1;
    }

    if (nextCol >= editableColumns.count) {
      nextCol = 0;
      nextRow += 1;
    } else if (nextCol < 0) {
      nextCol = editableColumns.count - 1;
      nextRow -= 1;
    }

    if (nextRow < 0) nextRow = 0;
    if (nextRow >= fields.length) {
      const canAppendRow = event.key === 'Enter' || event.key === 'Tab' || (!isRtlLayout && event.key === 'ArrowRight') || (isRtlLayout && event.key === 'ArrowLeft');
      if (canAppendRow && !(event.key === 'Tab' && event.shiftKey)) {
        appendEmptyRow();
        nextRow = fields.length;
        nextCol = 0;
      } else {
        nextRow = Math.max(0, fields.length - 1);
      }
    }

    setTimeout(() => focusCell(nextRow, nextCol), 0);
  }

  function handleInputKeyDown(event: React.KeyboardEvent<HTMLInputElement>, rowIndex: number, colIndex: number) {
    if (['Enter', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', '+', '-'].includes(event.key) || event.code === 'NumpadAdd' || event.code === 'NumpadSubtract') {
      handleGridKeyDown(event as unknown as React.KeyboardEvent<HTMLElement>, rowIndex, colIndex);
    }
  }

  function resolveRealEstateInvoiceContext(data: SalesInvoiceFormData) {
    if (!realEstateEnabled) {
      return {
        isRealEstate: false,
        projectId: '',
        projectName: undefined as string | undefined,
        unitId: '',
        unitName: undefined as string | undefined,
      };
    }

    const explicitProjectId = String(data.realEstateProjectId || '').trim();
    const explicitUnitId = String(data.realEstateUnitId || '').trim();
    const filledItems = (data.items || []).filter((item) => {
      const hasMaterial = Boolean(String(item.materialId || '').trim());
      const hasRealEstateUnit = Boolean(String(item.realEstateProjectId || '').trim() && String(item.realEstateUnitId || '').trim());
      return hasMaterial || hasRealEstateUnit;
    });
    const resolvedRefs = filledItems.reduce<Array<{ projectId: string; projectName?: string; unitId: string; unitName?: string }>>((acc, item) => {
      const material = materialById.get(String(item.materialId || '').trim());
      const projectId = String(item.realEstateProjectId || material?.realEstateProjectId || '').trim();
      const unitId = String(item.realEstateUnitId || material?.realEstateUnitId || '').trim();
      if (!projectId || !unitId) return acc;
      const project = realEstateProjectsById.get(projectId);
      const unit = getProjectUnitOptions(project).find((entry) => String(entry?.id || '').trim() === unitId);
      acc.push({
        projectId,
        projectName: String(item.realEstateProjectName || material?.realEstateProjectName || project?.name || '').trim() || undefined,
        unitId,
        unitName: String(item.realEstateUnitName || material?.realEstateUnitName || unit?.name || unit?.unitCode || '').trim() || undefined,
      });
      return acc;
    }, []);

    const uniqueRefs = Array.from(new Map(resolvedRefs.map((entry) => [`${entry.projectId}::${entry.unitId}`, entry])).values());
    const fallbackProject = realEstateProjectsById.get(explicitProjectId);
    const fallbackUnit = getProjectUnitOptions(fallbackProject).find((entry) => String(entry?.id || '').trim() === explicitUnitId);
    const primary = uniqueRefs[0] || (explicitProjectId && explicitUnitId
      ? {
          projectId: explicitProjectId,
          projectName: String(data.realEstateProjectName || fallbackProject?.name || '').trim() || undefined,
          unitId: explicitUnitId,
          unitName: String(data.realEstateUnitName || fallbackUnit?.name || fallbackUnit?.unitCode || '').trim() || undefined,
        }
      : undefined);

    if (!primary) {
      return {
        isRealEstate: false,
        error: 'لم يتم تحديد مشروع عقاري صالح من سطور الفاتورة.',
        projectId: '',
        projectName: undefined as string | undefined,
        unitId: '',
        unitName: undefined as string | undefined,
      };
    }

    if (uniqueRefs.length > 1) {
      return {
        isRealEstate: true,
        error: 'تم اكتشاف عدة وحدات عقارية مختلفة في أكثر من سطر من سطور الفاتورة.',
        ...primary,
      };
    }

    if (filledItems.length === 0) {
      return {
        isRealEstate: true,
        error: 'لا توجد بنود فاتورة في وضع العقار أو لم يتم إدخال بنود صالحة.',
        ...primary,
      };
    }

    const hasUnlinkedRows = filledItems.some((item) => {
      const material = materialById.get(String(item.materialId || '').trim());
      const projectId = String(item.realEstateProjectId || material?.realEstateProjectId || '').trim();
      const unitId = String(item.realEstateUnitId || material?.realEstateUnitId || '').trim();
      return !projectId || !unitId || `${projectId}::${unitId}` !== `${primary.projectId}::${primary.unitId}`;
    });

    if (hasUnlinkedRows) {
      return {
        isRealEstate: true,
        error: 'بعض السطور غير مرتبطة بالوحدة العقارية المحددة في رأس الفاتورة.',
        ...primary,
      };
    }

    return {
      isRealEstate: true,
      ...primary,
    };
  }

  function mapSalesUpdateError(error?: string): string {
    if (!error) return 'حدث خطأ غير متوقع أثناء الحفظ.';
    if (error === 'INVALID_SALES_ACTION_SIGNATURE') {
      return 'توقيع العملية غير صالح أو منتهي. يرجى إعادة تحميل الصفحة والمحاولة مجددا.';
    }
    if (error === 'Cannot edit posted invoices') {
      return 'لا يمكن تعديل فاتورة مرحلة. يلزم إجراء عكس/تسوية ثم إنشاء مستند بديل.';
    }
    if (error === 'Cannot edit shipped invoices') {
      return 'لا يمكن تعديل فاتورة تم شحنها. قم بإرجاع/عكس الشحنة أولاً ثم عدّل.';
    }
    return error;
  }

  async function submitPayload(payload: any) {
    const guardedPayload = {
      ...payload,
      __salesActionGuard: actionGuardToken,
    };

    if (mode === 'edit' && invoiceId) {
      const result = await handleUpdateSalesInvoice(invoiceId, guardedPayload);
      if (result.success) {
        toast({ title: 'تمّ التعديل', description: 'تمّ تحديث الفاتورة بنجاح.' });
        router.push(`/admin/sales/view/${invoiceId}`);
      } else {
        const errorMessage = mapSalesUpdateError(result.error);
        toast({ title: 'خطأ', description: errorMessage, variant: 'destructive' });
      }
      return;
    }

    const result = await handleCreateSalesInvoice(guardedPayload);
    if (result.success) {
      toast({ title: 'تمّ الحفظ', description: 'تمّ حفظ الفاتورة بنجاح.' });
      router.push(`/admin/sales/view/${result.data?.id}`);
    } else {
      const errorMessage = mapSalesUpdateError(result.error);
      toast({ title: 'خطأ', description: errorMessage, variant: 'destructive' });
    }
  }

  function buildPayload(data: SalesInvoiceFormData, applyLossAsDiscount: boolean) {
    const warnings: Array<{ index: number; materialName: string; cost: number; costCurrency: string; unitPrice: number; saleCurrency: string; quantity: number; lossPerUnit: number; lossAmount: number }> = [];
    const invoiceCurrencyCode = data.currencyCode || defaultCurrencyCode || '';
    const getExchangeRate = (code: string) => {
      if (!code) return 1;
      const entry = currencies.find((c) => c.code === code);
      return Number(entry?.exchangeRate || 1) || 1;
    };
    const realEstateContext = resolveRealEstateInvoiceContext(data);

    const activeItems = (data.items || []).filter((item) => !isEffectivelyEmptyLineItem(item));

    const items = activeItems.map((item, index) => {
      const material = materials.find((m) => m.id === item.materialId);
      const purchasePrice = Number(material?.purchasePrice || 0);
      const quantity = Math.max(0, Number(item.quantity || 0));
      const unitPrice = Math.max(0, Number(item.unitPrice || 0));

      const purchaseCurrencyCode = String((material as any)?.purchaseCurrencyCode || defaultCurrencyCode || "");
      let lineDiscountAmount = Number(item.lineDiscountAmount || 0);
      if (purchasePrice > 0 && quantity > 0) {
        // Convert both prices to base currency for cross-currency comparison
        const purchasePriceRate = getExchangeRate(purchaseCurrencyCode);
        const salePriceRate = getExchangeRate(invoiceCurrencyCode);
        const purchasePriceInBase = purchasePriceRate > 0 ? purchasePrice / purchasePriceRate : purchasePrice;
        const unitPriceInBase = salePriceRate > 0 ? unitPrice / salePriceRate : unitPrice;

        if (unitPriceInBase < purchasePriceInBase) {
          // Express loss per unit in the invoice currency
          const lossPerUnitInBase = purchasePriceInBase - unitPriceInBase;
          const lossPerUnit = lossPerUnitInBase * salePriceRate;
          const lossAmount = lossPerUnit * quantity;
          warnings.push({
            index: index + 1,
            materialName: material?.name || item.materialId,
            cost: purchasePrice,
            costCurrency: purchaseCurrencyCode,
            unitPrice,
            saleCurrency: invoiceCurrencyCode,
            quantity,
            lossPerUnit,
            lossAmount,
          });
          if (applyLossAsDiscount) {
            lineDiscountAmount += lossAmount;
          }
        }
      }

      return {
        ...item,
        lineDiscountAmount,
        warehouseId: warehousesEnabled ? (data.warehouseId || defaultWarehouseId || '') : undefined,
        name: item.name || material?.name || item.materialId,
        realEstateProjectId: realEstateContext.isRealEstate ? (realEstateContext.projectId || undefined) : undefined,
        realEstateProjectName: realEstateContext.isRealEstate ? (realEstateContext.projectName || undefined) : undefined,
        realEstateUnitId: realEstateContext.isRealEstate ? (realEstateContext.unitId || undefined) : undefined,
        realEstateUnitName: realEstateContext.isRealEstate ? (realEstateContext.unitName || undefined) : undefined,
      };
    });

    const selectedMethods = new Set(data.paymentMethodsSelected || []);
    const normalizedChecks = (data.paymentChecks || [])
      .filter((check) => String(check.checkNumber || '').trim())
      .map((check) => ({
        method: 'check' as const,
        amount: Number(check.amount || 0),
        currency: check.currency || data.currencyCode || defaultCurrencyCode || '',
        reference: check.reference || undefined,
        checkNumber: check.checkNumber,
        checkDate: check.checkDate,
        bankId: check.bankId,
        bankName: check.bankName,
        status: check.status || 'pending',
      }));

    const cashCollected = selectedMethods.has('cash') ? Number(data.cashAmount || 0) : 0;
    const checksCollected = selectedMethods.has('check')
      ? normalizedChecks.reduce((sum, check) => sum + Number(check.amount || 0), 0)
      : 0;
    const immediateAmountReceived = cashCollected + checksCollected;
    const deferredCreditAmount = selectedMethods.has('credit')
      ? Math.max(0, grandTotal - immediateAmountReceived)
      : 0;

    const paymentMethods = [
      ...(selectedMethods.has('cash') && cashCollected > 0
        ? [{
            method: 'cash' as const,
            amount: cashCollected,
            currency: data.currencyCode || defaultCurrencyCode || '',
          }]
        : []),
      ...(selectedMethods.has('check') ? normalizedChecks : []),
      ...(selectedMethods.has('credit')
        ? [{
            method: 'credit' as const,
            amount: deferredCreditAmount,
            currency: data.currencyCode || defaultCurrencyCode || '',
          }]
        : []),
    ];

    const { paymentChecks, paymentMethodsSelected, cashAmount, ...restData } = data;
    const resolvedContractValue = realEstateContext.isRealEstate
      ? Math.max(0, Number(data.realEstateContractValue || selectedRealEstateUnit?.actualSaleValue || selectedRealEstateUnit?.saleValue || grandTotal))
      : 0;
    const resolvedDownPayment = realEstateContext.isRealEstate ? Math.max(0, immediateAmountReceived) : 0;
    const resolvedDeferredAmount = realEstateContext.isRealEstate ? Math.max(0, resolvedContractValue - resolvedDownPayment) : 0;

    const payload = {
      ...restData,
      amountReceived: immediateAmountReceived,
      secondaryCustomerId: String(data.secondaryCustomerId || '').trim() || undefined,
      primaryCoveragePercent: primaryCoveragePercent,
      secondaryCoveragePercent: normalizedSecondaryCoveragePercent,
      primaryCoverageAmount: Number(((Number(grandTotal || 0) * primaryCoveragePercent) / 100).toFixed(2)),
      secondaryCoverageAmount: Number(((Number(grandTotal || 0) * normalizedSecondaryCoveragePercent) / 100).toFixed(2)),
      salesRepId: salesRepsEnabled ? (data.salesRepId || undefined) : undefined,
      userId,
      userName,
      items,
      paymentMethods,
      realEstateProjectId: realEstateContext.isRealEstate ? (realEstateContext.projectId || undefined) : undefined,
      realEstateProjectName: realEstateContext.isRealEstate ? (realEstateContext.projectName || undefined) : undefined,
      realEstateUnitId: realEstateContext.isRealEstate ? (realEstateContext.unitId || undefined) : undefined,
      realEstateUnitName: realEstateContext.isRealEstate ? (realEstateContext.unitName || undefined) : undefined,
      realEstateContractNumber: realEstateContext.isRealEstate ? (String(data.realEstateContractNumber || '').trim() || undefined) : undefined,
      realEstateContractDate: realEstateContext.isRealEstate ? (String(data.realEstateContractDate || '').trim() || undefined) : undefined,
      realEstateHandoverDate: realEstateContext.isRealEstate ? (String(data.realEstateHandoverDate || '').trim() || undefined) : undefined,
      realEstateContractValue: realEstateContext.isRealEstate ? resolvedContractValue : undefined,
      realEstateDownPayment: realEstateContext.isRealEstate ? resolvedDownPayment : undefined,
      realEstateDeferredAmount: realEstateContext.isRealEstate ? resolvedDeferredAmount : undefined,
      realEstateInstallmentMode: realEstateContext.isRealEstate ? (data.realEstateInstallmentMode || 'existing') : undefined,
      realEstateInstallmentCount: realEstateContext.isRealEstate ? Math.max(0, Number(data.realEstateInstallmentCount || 0)) : undefined,
      realEstateFirstDueDate: realEstateContext.isRealEstate ? (String(data.realEstateFirstDueDate || '').trim() || undefined) : undefined,
      realEstateInstallmentInterval: realEstateContext.isRealEstate ? (data.realEstateInstallmentInterval || 'monthly') : undefined,
      documentType: shipmentWorkflowEnabled ? documentType : 'tax_invoice',
      linkedShipmentIds: shipmentWorkflowEnabled && documentType === 'tax_invoice' && linkedShipmentIds.length > 0
        ? linkedShipmentIds
        : undefined,
    };

    return { payload, warnings };
  }

  async function continueSaveWithLossHandling() {
    if (!pendingLossPayload) return;
    try {
      setIsSubmitting(true);
      setShowLossDialog(false);
      const payload = pendingLossPayload;
      setPendingLossPayload(null);

      if (mode === 'create') {
        setPendingPostingPayload(payload);
        const defaultPostingType: PostingType = (shipmentWorkflowEnabled && documentType === 'shipment')
          ? 'saved'
          : (payload?.realEstateProjectId && payload?.realEstateUnitId ? 'posted' : 'saved');
        setSelectedPostingType(defaultPostingType);
        setShowPostingDialog(true);
        return;
      }

      await submitPayload(payload);
    } finally {
      setIsSubmitting(false);
    }
  }

  async function confirmPostingAndSave() {
    if (!pendingPostingPayload) return;
    try {
      setIsSubmitting(true);
      await submitPayload({
        ...pendingPostingPayload,
        postingStatus: selectedPostingType,
      });
      setShowPostingDialog(false);
      setPendingPostingPayload(null);
    } finally {
      setIsSubmitting(false);
    }
  }

  const onSubmit = async (data: SalesInvoiceFormData) => {
    if (isEditLockedByStatus) {
      toast({ title: 'تعديل غير متاح', description: editLockReason, variant: 'destructive' });
      return;
    }

    try {
      setIsSubmitting(true);
      const activeItemsCount = (data.items || []).filter((item) => !isEffectivelyEmptyLineItem(item)).length;
      const hasLinkedShipments = shipmentWorkflowEnabled
        && documentType === 'tax_invoice'
        && linkedShipmentIds.length > 0;
      if (activeItemsCount === 0 && !hasLinkedShipments) {
        setActiveTab('items');
        toast({ title: 'تحذير', description: 'يرجى إضافة سطر واحد على الأقل.', variant: 'destructive' });
        setIsSubmitting(false);
        return;
      }

      const realEstateContext = resolveRealEstateInvoiceContext(data);
      if ('error' in realEstateContext && realEstateContext.error) {
        setActiveTab('items');
        toast({ title: 'خطأ بيانات عقارية', description: realEstateContext.error, variant: 'destructive' });
        setIsSubmitting(false);
        return;
      }
      if (warehousesEnabled && !data.warehouseId) {
        toast({ title: 'تحذير', description: 'يجب اختيار مستودع عند تفعيل المستودعات.', variant: 'destructive' });
        setIsSubmitting(false);
        return;
      }
      const { payload, warnings } = buildPayload(data, false);

      if (warnings.length > 0) {
        setLossWarnings(warnings);
        if (blockSalesBelowCost) {
          setPendingLossPayload(null);
        } else {
          const adjusted = buildPayload(data, true).payload;
          setPendingLossPayload(adjusted);
        }
        setShowLossDialog(true);
        setIsSubmitting(false);
        return;
      }

      if (mode === 'create') {
        setPendingPostingPayload(payload);
        setSelectedPostingType((shipmentWorkflowEnabled && documentType === 'shipment')
          ? 'saved'
          : (realEstateContext.isRealEstate ? 'posted' : 'saved'));
        setShowPostingDialog(true);
        setIsSubmitting(false);
        return;
      }

      await submitPayload(payload);
    } catch {
      toast({ title: 'خطأ', description: 'حدث خطأ أثناء الحفظ.', variant: 'destructive' });
    } finally {
      setIsSubmitting(false);
    }
  };

  const onInvalidSubmit = () => {
    const errors = form.formState.errors;

    if (errors.paymentMethodsSelected || errors.cashAmount || errors.paymentChecks) {
      setActiveTab('payment');
    } else if (errors.customerNotes || errors.internalNotes) {
      setActiveTab('notes');
    } else {
      setActiveTab('items');
    }

    toast({
      title: 'أخطاء في النموذج',
      description: 'يوجد أخطاء في بعض الحقول. يرجى مراجعة وتصحيحها.',
      variant: 'destructive',
    });
  };

  useEffect(() => {
    const handleShortcut = (event: KeyboardEvent) => {
      if (event.key !== 'F2' || event.repeat) return;
      event.preventDefault();
      if (isSubmitting || isEditLockedByStatus) return;
      void form.handleSubmit(onSubmit, onInvalidSubmit)();
    };

    window.addEventListener('keydown', handleShortcut);
    return () => window.removeEventListener('keydown', handleShortcut);
  }, [form, isSubmitting, isEditLockedByStatus, onSubmit]);

  return (
    <Card>
      <CardHeader>
        <CardTitle>
          {mode === 'create' ? 'إنشاء فاتورة مبيعات' : 'تعديل الفاتورة'}
        </CardTitle>
        {isEditLockedByStatus && (
          <p className="mt-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900">
            {editLockReason}
          </p>
        )}
      </CardHeader>

      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit, onInvalidSubmit)} className="space-y-6">

            <div className="rounded-lg border bg-muted/15 p-4 space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
                <FormItem id="sales-auto-doc-number">
                  <FormLabel>رقم المستند</FormLabel>
                  <FormControl>
                    <Input value="يُحدد تلقائيًا عند الحفظ" readOnly disabled />
                  </FormControl>
                </FormItem>

                <FormField
                  control={form.control}
                  name="manualDocNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>رقم المرجع اليدوي</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="اختياري" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="customerId"
                  render={({ field }) => (
                    <FormItem className="md:col-span-1 lg:col-span-2">
                      <FormLabel htmlFor="sales-customer-selector">العميل *</FormLabel>
                      <FormControl>
                        <PartySelector
                          id="sales-customer-selector"
                          value={field.value}
                          options={customers}
                          onValueChange={(id) => {
                            field.onChange(id);
                            if (form.getValues('secondaryCustomerId') === id) {
                              form.setValue('secondaryCustomerId', '', { shouldDirty: true, shouldValidate: true });
                              form.setValue('secondaryCoveragePercent', 0, { shouldDirty: true, shouldValidate: true });
                            }
                            const cust = customers.find((c) => c.id === id);
                            if (salesRepsEnabled && cust?.salesRepId) {
                              form.setValue('salesRepId', cust.salesRepId);
                            } else if (!salesRepsEnabled) {
                              form.setValue('salesRepId', '');
                            }
                          }}
                          placeholder="اختر عميلاً"
                          searchPlaceholder="ابحث عن عميل..."
                          emptyLabel="لا توجد نتائج"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="secondaryCustomerId"
                  render={({ field }) => (
                    <FormItem className="md:col-span-1 lg:col-span-2">
                      <FormLabel htmlFor="sales-secondary-customer-selector">العميل الثانوي (اختياري)</FormLabel>
                      <FormControl>
                        <PartySelector
                          id="sales-secondary-customer-selector"
                          value={field.value}
                          options={customers.filter((entry) => entry.id !== form.getValues('customerId'))}
                          onValueChange={field.onChange}
                          placeholder="اختر عميلاً ثانوياً"
                          searchPlaceholder="ابحث عن عميل..."
                          emptyLabel="لا توجد نتائج"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="secondaryCoveragePercent"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>نسبة تغطية العميل الثانوي %</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min={0}
                          max={100}
                          step="0.01"
                          value={Number(field.value || 0)}
                          onChange={(event) => field.onChange(Number(event.target.value || 0))}
                          disabled={!String(watchedSecondaryCustomerId || '').trim()}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormItem>
                  <FormLabel>نسبة تغطية العميل الرئيسي %</FormLabel>
                  <FormControl>
                    <Input value={primaryCoveragePercent.toFixed(2)} readOnly disabled />
                  </FormControl>
                </FormItem>

                <FormField
                  control={form.control}
                  name="date"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>تاريخ الفاتورة *</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {salesRepsEnabled && salesReps.length > 0 && (
                  <FormField
                    control={form.control}
                    name="salesRepId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>مندوب المبيعات</FormLabel>
                        <Select value={field.value ?? ''} onValueChange={field.onChange}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="اختر مندوبًا" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {salesReps.map((rep) => (
                              <SelectItem key={rep.id} value={rep.id}>
                                {rep.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                {warehousesEnabled && warehouses.length > 0 && (
                  <FormField
                    control={form.control}
                    name="warehouseId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>المستودع (افتراضي للفواتير)</FormLabel>
                        <Select value={field.value ?? ''} onValueChange={field.onChange} dir="rtl">
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="اختر مستودعًا" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {warehouses.map((wh) => (
                              <SelectItem key={wh.id} value={wh.id}>
                                {wh.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {currencies.length > 0 && (
                  <FormField
                    control={form.control}
                    name="currencyCode"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>العملة</FormLabel>
                        <Select value={field.value ?? ''} onValueChange={(val) => {
                          field.onChange(val);
                          const cur = currencies.find((c) => c.code === val);
                          if (cur?.exchangeRate) {
                            form.setValue('exchangeRate', cur.exchangeRate);
                          }
                        }}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="اختر العملة" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {currencies.map((cur) => (
                              <SelectItem key={cur.code} value={cur.code}>
                                {cur.name} ({cur.code})
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                <FormField
                  control={form.control}
                  name="exchangeRate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>سعر الصرف</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.0001"
                          min={0}
                          {...field}
                          onChange={(e) => field.onChange(parseFloat(e.target.value) || 1)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

              </div>
              {/* Document Type Toggle — Sales Shipment Workflow */}
              {shipmentWorkflowEnabled && (
                <div className="flex flex-wrap items-center gap-3 pt-1">
                  <span className="text-sm font-medium">نوع المستند:</span>
                  <div className="inline-flex overflow-hidden rounded-md border divide-x rtl:divide-x-reverse">
                    <button
                      type="button"
                      className={`px-4 py-1.5 text-sm font-medium transition-colors ${documentType === 'shipment' ? 'bg-amber-500 text-white' : 'bg-background text-foreground hover:bg-muted'}`}
                      onClick={() => setDocumentType('shipment')}
                    >
                      ارسالية
                    </button>
                    <button
                      type="button"
                      className={`px-4 py-1.5 text-sm font-medium transition-colors ${documentType === 'tax_invoice' ? 'bg-primary text-primary-foreground' : 'bg-background text-foreground hover:bg-muted'}`}
                      onClick={() => setDocumentType('tax_invoice')}
                    >
                      فاتورة ضريبية
                    </button>
                  </div>
                  {documentType === 'shipment' && (
                    <span className="rounded border border-amber-200 bg-amber-50 px-2 py-0.5 text-xs text-amber-700">
                      يؤثر على المخزون فقط — بدون قيد محاسبي
                    </span>
                  )}
                </div>
              )}

              {/* Link shipments to this tax invoice */}
              {shipmentWorkflowEnabled && documentType === 'tax_invoice' && mode === 'create' && watchedCustomerId && (
                <div className="border rounded-md p-3 bg-muted/30 space-y-2">
                  <p className="text-sm font-medium">ربط بإرساليات سابقة</p>
                  {isFetchingShipments ? (
                    <p className="text-xs text-muted-foreground">جارٍ تحميل الإرساليات...</p>
                  ) : availableShipments.length === 0 ? (
                    <p className="text-xs text-muted-foreground">لا توجد إرساليات غير مرتبطة لهذا العميل.</p>
                  ) : (
                    <div className="space-y-1 max-h-48 overflow-y-auto">
                      {availableShipments.map((shp) => {
                        const checked = linkedShipmentIds.includes(shp.id);
                        return (
                          <label key={shp.id} className="flex items-center gap-2 cursor-pointer rounded px-2 py-1 hover:bg-muted text-sm">
                            <input
                              type="checkbox"
                              checked={checked}
                              onChange={() => {
                                const nowChecked = !checked;
                                setLinkedShipmentIds((prev) =>
                                  nowChecked ? [...prev, shp.id] : prev.filter((id) => id !== shp.id)
                                );
                                if (nowChecked && Array.isArray(shp.items) && shp.items.length > 0) {
                                  // Auto-import items from the linked shipment (same as purchase form behavior)
                                  const newItems = shp.items
                                    .filter((item) => Number(item.quantity || 0) > 0)
                                    .map((item) => ({
                                      materialId: item.materialId || '',
                                      name: item.name || '',
                                      quantity: Number(item.quantity || 0),
                                      unitPrice: Number(item.unitPrice || 0),
                                      lineDiscountPercent: Number(item.lineDiscountPercent || 0),
                                      lineDiscountAmount: Number(item.lineDiscountAmount || 0),
                                      taxRate: Number(item.taxRate || 0),
                                      shelfId: item.shelfId || '',
                                      description: item.description || '',
                                      realEstateProjectId: item.realEstateProjectId || '',
                                      realEstateProjectName: item.realEstateProjectName || '',
                                      realEstateUnitId: item.realEstateUnitId || '',
                                      realEstateUnitName: item.realEstateUnitName || '',
                                    }));
                                  const currentItems = form.getValues('items') || [];
                                  const nonEmptyItems = currentItems.filter(
                                    (gi) => String(gi.materialId || '').trim() || String(gi.realEstateProjectId || '').trim()
                                  );
                                  form.setValue('items', [...nonEmptyItems, ...newItems], { shouldDirty: true, shouldValidate: false });
                                }
                              }}
                              className="h-4 w-4 rounded border-gray-300"
                            />
                            <span className="font-mono font-medium">{shp.invoiceNumber}</span>
                            <span className="text-muted-foreground">
                              — {formatDateDDMMYYYY(shp.date)}
                            </span>
                            <span className="font-mono ms-auto">
                              {shp.grandTotal.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} {shp.currencyCode || ''}
                            </span>
                          </label>
                        );
                      })}
                    </div>
                  )}
                  {linkedShipmentIds.length > 0 && (
                    <p className="text-xs text-primary font-medium">
                      تم اختيار {linkedShipmentIds.length} إرسالية للربط
                    </p>
                  )}
                </div>
              )}


              {realEstateEnabled && (
                <div className="border-t pt-4">
                  <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <FormField
                      control={form.control}
                      name="realEstateProjectId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>المشروع / الوحدة</FormLabel>
                          <Select
                            value={field.value || ''}
                            onValueChange={(value) => {
                              field.onChange(value);
                              const project = realEstateProjectsById.get(value);
                              form.setValue('realEstateProjectName', String(project?.name || '').trim(), { shouldDirty: true, shouldValidate: false });
                              form.setValue('realEstateUnitId', '', { shouldDirty: true, shouldValidate: false });
                              form.setValue('realEstateUnitName', '', { shouldDirty: true, shouldValidate: false });
                              updateItem(0, 'materialId', '');
                              updateItem(0, 'name', '');
                              updateItem(0, 'quantity', 1);
                              updateItem(0, 'unitPrice', 0);
                              updateItem(0, 'lineDiscountPercent', 0);
                              updateItem(0, 'lineDiscountAmount', 0);
                            }}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="اختر مشروعاً" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {realEstateProjects.map((project) => (
                                <SelectItem key={project.id} value={project.id}>
                                  {project.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormItem id="sales-selected-real-estate-unit">
                      <FormLabel>الطابق / الوحدة العقارية</FormLabel>
                      <FormControl>
                        {requiresEngineeringSectionSelection ? (
                          <Popover open={isSectionPickerOpen} onOpenChange={setIsSectionPickerOpen}>
                            <PopoverTrigger asChild>
                              <Button
                                type="button"
                                variant="outline"
                                role="combobox"
                                className={`w-full justify-between text-sm ${selectedRealEstateDisplayLabel ? '' : 'text-muted-foreground'}`}
                                disabled={!String(watchedRealEstateProjectId || '').trim()}
                              >
                                <span className="truncate">
                                  {selectedRealEstateDisplayLabel || (String(watchedRealEstateProjectId || '').trim()
                                    ? 'اختر الوحدة من القائمة'
                                    : 'اختر المشروع أولاً')}
                                </span>
                                <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent align="start" className="w-[min(92vw,560px)] p-3">
                              <div className="space-y-3">
                                <div>
                                  <p className="text-sm font-medium">اختر الوحدة العقارية من الطابق</p>
                                  <p className="text-xs text-muted-foreground">اضغط على بطاقة لعرض الوحدات المتاحة في ذلك الطابق.</p>
                                </div>
                                <div className="grid gap-3">
                                  {realEstateSectionCards.map((section) => {
                                    const isSelectedSection = String(selectedRealEstateFloorDetail?.id || '').trim() === String(section.id || '').trim();
                                    return (
                                      <button
                                        key={section.id}
                                        type="button"
                                        onClick={() => {
                                          setSelectedRealEstateSectionId(section.id);
                                          setIsSectionPickerOpen(false);
                                          const currentUnitFloor = normalizeComparableLabel(selectedRealEstateUnit?.floor);
                                          const targetFloorLabel = normalizeComparableLabel(section.floorLabel);
                                          const isSameSection = currentUnitFloor
                                            && (currentUnitFloor === targetFloorLabel || currentUnitFloor.includes(targetFloorLabel) || targetFloorLabel.includes(currentUnitFloor));
                                          if (!isSameSection) {
                                            form.setValue('realEstateUnitId', '', { shouldDirty: true, shouldValidate: false });
                                            form.setValue('realEstateUnitName', '', { shouldDirty: true, shouldValidate: false });
                                            updateItem(0, 'materialId', '');
                                            updateItem(0, 'name', '');
                                            updateItem(0, 'unitPrice', 0);
                                          }
                                        }}
                                        className={`rounded-2xl border bg-card p-3 text-start shadow-sm space-y-3 transition-colors ${isSelectedSection ? 'border-emerald-600 bg-emerald-50' : 'hover:bg-accent/40'}`}
                                      >
                                        <div className="flex flex-wrap items-start justify-between gap-3">
                                          <div className="space-y-2">
                                            <div>
                                              <div className="text-sm font-semibold">{section.floorLabel}</div>
                                              <div className="text-xs text-muted-foreground">{section.description || `طابق ${section.floorLabel}`}</div>
                                            </div>
                                            <div className="flex flex-wrap gap-2 text-[11px]">
                                              <span className="rounded-full bg-muted px-2.5 py-1 font-medium text-foreground/80">{section.usageLabel}</span>
                                              <span className="rounded-full border bg-background px-2.5 py-1 text-muted-foreground">عدد الوحدات/الدور: {section.unitCount}</span>
                                              {section.areaLabel && (
                                                <span className="rounded-full border bg-background px-2.5 py-1 text-muted-foreground">{section.areaLabel}</span>
                                              )}
                                            </div>
                                          </div>
                                          <div className="rounded-md border bg-background px-3 py-1.5 text-xs text-muted-foreground">
                                            {isSelectedSection ? 'محدد حالياً' : 'اختر هذا الطابق'}
                                          </div>
                                        </div>
                                      </button>
                                    );
                                  })}
                                </div>
                              </div>
                            </PopoverContent>
                          </Popover>
                        ) : (
                          <Input
                            readOnly
                            value={
                              selectedRealEstateDisplayLabel
                              || (String(watchedRealEstateProjectId || '').trim()
                                ? 'اختر وحدة من بنود الفاتورة'
                                : 'اختر المشروع أولاً')
                            }
                          />
                        )}
                      </FormControl>
                      <p className="text-xs text-muted-foreground">
                        هذا الصنف مرتبط مباشرةً بوحدة عقارية. لا يمكن تعيين وحدة مختلفة من بنود الفاتورة.
                      </p>
                      {String(watchedRealEstateUnitId || '').trim() && (
                        <div className="flex flex-wrap gap-2 pt-1 text-[11px]">
                          {(selectedRealEstateFloorDetail?.floorLabel || selectedRealEstateUnit?.floor) && (
                            <span className="rounded-full border bg-background px-2.5 py-1 text-muted-foreground">
                              {selectedRealEstateFloorDetail?.floorLabel || selectedRealEstateUnit?.floor}
                            </span>
                          )}
                          {selectedRealEstateUsageLabel && (
                            <span className="rounded-full bg-muted px-2.5 py-1 font-medium text-foreground/80">
                              {selectedRealEstateUsageLabel}
                            </span>
                          )}
                          {Number(selectedRealEstateEngineeringUnitDetail?.area || selectedRealEstateUnit?.area || 0) > 0 && (
                            <span className="rounded-full border bg-background px-2.5 py-1 text-muted-foreground">
                              المساحة: {formatDecimal(Number(selectedRealEstateEngineeringUnitDetail?.area || selectedRealEstateUnit?.area || 0), 2)} م²
                            </span>
                          )}
                        </div>
                      )}
                    </FormItem>
                  </div>
                </div>
              )}
            </div>

            {/* -- Tabs -- */}
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList
                className={`inline-flex h-10 w-full items-center justify-start rounded-md p-1 ${documentType === 'shipment' ? 'bg-amber-500 text-amber-50' : 'bg-emerald-700 text-emerald-100'}`}
                dir="rtl"
              >
                <TabsTrigger value="items" className="flex-1 data-[state=active]:bg-background data-[state=active]:text-foreground">بنود الفاتورة</TabsTrigger>
                {realEstateEnabled && (
                  <TabsTrigger value="real-estate" className="flex-1 data-[state=active]:bg-background data-[state=active]:text-foreground">
                    العقار والوحدة
                  </TabsTrigger>
                )}
                <TabsTrigger value="payment" className="flex-1 data-[state=active]:bg-background data-[state=active]:text-foreground">الدفع</TabsTrigger>
                <TabsTrigger value="notes" className="flex-1 data-[state=active]:bg-background data-[state=active]:text-foreground">ملاحظات</TabsTrigger>
                <TabsTrigger value="log" className="flex-1 data-[state=active]:bg-background data-[state=active]:text-foreground">LOG</TabsTrigger>
              </TabsList>

              {/* -- Items Tab -- */}
              <TabsContent value="items" className="mt-4 space-y-3">
                <div dir={isRtlLayout ? 'rtl' : 'ltr'} className="space-y-3 rounded-md border p-3">
                  <div className="rounded-md border overflow-x-auto">
                    <Table className="w-full table-fixed text-sm [&_th]:border-s [&_th]:border-border/70 [&_th:first-child]:border-s-0 [&_td]:border-s [&_td]:border-border/40 [&_td:first-child]:border-s-0 [&_th]:p-2 [&_td]:p-2 [&_th]:bg-muted/40 [&_th]:text-xs [&_th]:font-medium [&_th]:text-start [&_td]:align-middle [&_input]:h-9 [&_input]:text-sm [&_button[role=combobox]]:h-9">
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[58px] text-center">#</TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'item' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.item}px`, minWidth: `${columnWidths.item}px` }}>
                            {realEstateEnabled ? 'الصنف / الوحدة العقارية' : 'الصنف'}
                            {renderResizeHandle('item')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'quantity' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.quantity}px`, minWidth: `${columnWidths.quantity}px` }}>
                            الكمية
                            {renderResizeHandle('quantity')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'unitPrice' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.unitPrice}px`, minWidth: `${columnWidths.unitPrice}px` }}>
                            سعر الوحدة
                            {renderResizeHandle('unitPrice')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'discountPercent' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.discountPercent}px`, minWidth: `${columnWidths.discountPercent}px` }}>
                            خصم %
                            {renderResizeHandle('discountPercent')}
                          </TableHead>
                          <TableHead className={`group relative ${resizingColumnKey === 'taxRate' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.taxRate}px`, minWidth: `${columnWidths.taxRate}px` }}>
                            ضريبة %
                            {renderResizeHandle('taxRate')}
                          </TableHead>
                          {warehousesEnabled && warehouses.length > 0 && (
                            <TableHead className={`group relative ${resizingColumnKey === 'shelf' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.shelf}px`, minWidth: `${columnWidths.shelf}px` }}>
                              الرف
                              {renderResizeHandle('shelf')}
                            </TableHead>
                          )}
                          <TableHead className={`group relative text-end ${resizingColumnKey === 'total' ? 'bg-emerald-50' : ''}`} style={{ width: `${columnWidths.total}px`, minWidth: `${columnWidths.total}px` }}>
                            الإجمالي
                            {renderResizeHandle('total')}
                          </TableHead>
                          <TableHead className="w-[120px] text-right" />
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {fields.map((field, index) => {
                          const item = watchedItems?.[index] ?? field;
                          const lineNet = getEffectiveLineNet(item, index);
                          const rowCampaignPreviewDiscount = Number(campaignPreview.discountByLineKey[String(index)] || 0);
                          const itemCol = editableColumns.item;
                          const quantityCol = editableColumns.quantity;
                          const unitPriceCol = editableColumns.unitPrice;
                          const discountPercentCol = editableColumns.discountPercent;
                          const taxRateCol = editableColumns.taxRate;
                          const shelfCol = editableColumns.shelf;
                          const totalCol = editableColumns.total;
                          const rowShelfOptions = stockShelfOptionsByRow[index] || [];
                          const hasMultipleShelves = hasMultipleShelvesByRow[index] === true;
                          const selectedMaterial = String(item?.materialId || '').trim()
                            ? materialById.get(String(item.materialId || '').trim())
                            : undefined;
                          const fallbackSelectedUnitLabel = index === 0
                            ? String(selectedRealEstateUnit?.name || selectedRealEstateUnit?.unitCode || '').trim()
                            : '';
                          const selectedUnitLabel = String(
                            item?.realEstateUnitName
                            || selectedMaterial?.realEstateUnitName
                            || fallbackSelectedUnitLabel
                            || item?.name
                            || selectedMaterial?.name
                            || item?.materialId
                            || ''
                          ).trim();
                          const hasMaterialSelected = Boolean(String(item?.materialId || '').trim());
                          const hasRowSelection = hasMaterialSelected || Boolean(selectedUnitLabel);
                          return (
                            <TableRow
                              key={field.id}
                                className="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted"
                                onDragOver={(event) => event.preventDefault()}
                                onDrop={(event) => {
                                  event.preventDefault();
                                  if (draggingRowIndex === null || draggingRowIndex === index) {
                                    setDraggingRowIndex(null);
                                    return;
                                  }
                                  move(draggingRowIndex, index);
                                  setDraggingRowIndex(null);
                                  setTimeout(() => focusCell(index, itemCol), 0);
                                }}
                              >
                              <TableCell className="text-center text-xs text-muted-foreground">
                                <div className="flex items-center justify-center gap-1">
                                  <span lang="en" dir="ltr" className="font-mono">{index + 1}</span>
                                  <button
                                    type="button"
                                    draggable
                                    title="سحب لإعادة الترتيب"
                                    className="inline-flex h-6 w-6 items-center justify-center rounded border border-dashed text-muted-foreground hover:bg-muted"
                                    onDragStart={() => setDraggingRowIndex(index)}
                                    onDragEnd={() => setDraggingRowIndex(null)}
                                  >
                                    <ChevronsUpDown className="h-3.5 w-3.5" />
                                  </button>
                                </div>
                              </TableCell>
                              <TableCell>
                                <button
                                  type="button"
                                  data-cell={`${index}-${itemCol}`}
                                  className={`w-full min-w-0 h-9 rounded-md border px-2.5 py-2 text-sm text-start flex items-center gap-1 focus:outline-none focus:ring-2 focus:ring-ring hover:bg-muted/50 truncate ${hasRowSelection ? '' : 'text-muted-foreground'}`}
                                  onClick={() => {
                                    if (realEstateEnabled && !String(watchedRealEstateProjectId || '').trim()) return;
                                    if (realEstateEnabled && requiresEngineeringSectionSelection && !String(selectedRealEstateFloorDetail?.id || '').trim()) return;
                                    openPickerForRow(index);
                                  }}
                                  onKeyDown={(event) => handleGridKeyDown(event, index, itemCol)}
                                  disabled={realEstateEnabled && (!String(watchedRealEstateProjectId || '').trim() || (requiresEngineeringSectionSelection && !String(selectedRealEstateFloorDetail?.id || '').trim()))}
                                >
                                  <span className="truncate">
                                    {realEstateEnabled
                                      ? (selectedUnitLabel || (!String(watchedRealEstateProjectId || '').trim()
                                          ? 'اختر مشروعاً أولاً'
                                          : (requiresEngineeringSectionSelection && !String(selectedRealEstateFloorDetail?.id || '').trim())
                                            ? 'اختر القسم أولاً'
                                            : 'اختر وحدة عقارية'))
                                      : (() => {
                                          const materialName = selectedMaterial?.name || item.materialId || 'اختر صنفًا';
                                          const unitLabel = getMaterialPrimaryUnitLabel(selectedMaterial);
                                          return unitLabel ? `${materialName} / ${unitLabel}` : materialName;
                                        })()}
                                  </span>
                                  <ChevronDown className="h-3.5 w-3.5 shrink-0 ms-auto opacity-50" />
                                </button>
                                {form.formState.errors.items?.[index]?.materialId && (
                                  <p className="text-xs text-destructive mt-1">
                                    {form.formState.errors.items[index]?.materialId?.message}
                                  </p>
                                )}
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${quantityCol}`}
                                  key={`${index}-quantity-${formatDecimal(Number(item.quantity||0),3)}`}
                                  defaultValue={formatDecimal(Number(item.quantity||0), 3)}
                                  onBlur={(e) => commitLineNumber(index, 'quantity', e.target.value, { min: 0.001, fallback: 1 })}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, quantityCol)}
                                  disabled={realEstateEnabled}
                                />
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${unitPriceCol}`}
                                  key={`${index}-unitPrice-${formatDecimal(Number(item.unitPrice||0),2)}`}
                                  defaultValue={formatDecimal(Number(item.unitPrice||0), 2)}
                                  onBlur={(e) => commitLineNumber(index, 'unitPrice', e.target.value, { min: 0, fallback: 0 })}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, unitPriceCol)}
                                />
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${discountPercentCol}`}
                                  placeholder="0.00"
                                  key={`${index}-discPct-${formatDecimal(Number(item.lineDiscountPercent||0),2)}`}
                                  defaultValue={formatDecimal(Number(item.lineDiscountPercent||0), 2)}
                                  onBlur={(e) => {
                                    commitLineNumber(index, 'lineDiscountPercent', e.target.value, { min: 0, max: 100, fallback: 0 });
                                    updateItem(index, 'lineDiscountAmount', 0);
                                  }}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, discountPercentCol)}
                                />
                              </TableCell>
                              <TableCell>
                                <Input
                                  type="text"
                                  className="h-9 text-sm w-full min-w-0 text-center font-mono"
                                  lang="en"
                                  dir="ltr"
                                  inputMode="decimal"
                                  data-cell={`${index}-${taxRateCol}`}
                                  placeholder="0.00"
                                  key={`${index}-taxRate-${formatDecimal(Number(item.taxRate||0),2)}`}
                                  defaultValue={formatDecimal(Number(item.taxRate||0), 2)}
                                  onBlur={(e) => commitLineNumber(index, 'taxRate', e.target.value, { min: 0, max: 100, fallback: 0 })}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event, index, taxRateCol)}
                                />
                              </TableCell>
                              {warehousesEnabled && warehouses.length > 0 && typeof shelfCol === 'number' && (
                                <TableCell>
                                  <Select
                                    dir="rtl"
                                    value={item.shelfId || ''}
                                    onValueChange={(shelfId) => updateItem(index, 'shelfId', shelfId)}
                                  >
                                    <SelectTrigger
                                      className={`h-9 text-sm ${hasMultipleShelves && !item.shelfId ? 'border-red-500 ring-red-200 focus:ring-red-300' : ''}`}
                                      data-cell={`${index}-${shelfCol}`}
                                      onKeyDown={(event) => handleGridKeyDown(event, index, shelfCol)}
                                      disabled={!hasMaterialSelected || !watchedWarehouseId || rowShelfOptions.length === 0}
                                    >
                                      <SelectValue
                                        placeholder={
                                          !hasMaterialSelected
                                            ? 'اختر صنفًا أولًا'
                                            : !watchedWarehouseId
                                            ? 'اختر المستودع أولًا'
                                            : hasMultipleShelves && !item.shelfId
                                              ? 'اختر رفًا'
                                              : '-'
                                        }
                                      />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {rowShelfOptions.map((shelf) => (
                                        <SelectItem key={shelf.id} value={shelf.id}>
                                          {shelf.name}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </TableCell>
                              )}
                              <TableCell className="text-end text-sm font-medium" lang="en" dir="ltr">
                                <div className="space-y-1">
                                  <Input
                                    type="text"
                                    tabIndex={0}
                                    className="h-9 text-sm w-full min-w-0 text-end font-mono"
                                    key={`${index}-total-${formatDecimal(lineNet,2)}`}
                                    defaultValue={formatDecimal(lineNet, 2)}
                                    data-cell={`${index}-${totalCol}`}
                                    onBlur={(event) => commitLineTotal(index, event.target.value)}
                                    onFocus={selectAllOnFocus}
                                    onMouseDown={ensureSelectOnMouseDown}
                                    onKeyDown={(event) => handleInputKeyDown(event, index, totalCol)}
                                  />
                                  {rowCampaignPreviewDiscount > 0 && (
                                    <p className="text-xs text-emerald-700 text-start" dir="rtl">
                                      خصم الحملة (تقديري): -{rowCampaignPreviewDiscount.toFixed(2)}
                                    </p>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell>
                                <div className="flex items-center justify-center gap-1">
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                    title="تحريك السطر للأعلى (-)"
                                    onClick={() => move(index, Math.max(0, index - 1))}
                                    disabled={index === 0}
                                  >
                                    <span className="text-base leading-none">-</span>
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                    title="تحريك السطر للأسفل (+)"
                                    onClick={() => move(index, Math.min(fields.length - 1, index + 1))}
                                    disabled={index === fields.length - 1}
                                  >
                                    <span className="text-base leading-none">+</span>
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-8 w-8"
                                    onClick={() => remove(index)}
                                    disabled={fields.length === 1}
                                  >
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </div>
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  </div>
                  {!realEstateEnabled && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={appendEmptyRow}
                    >
                      <PlusCircle className="h-4 w-4 me-2" />
                      إضافة سطر
                    </Button>
                  )}
                  {form.formState.errors.items?.root?.message && (
                    <p className="text-sm text-destructive">{form.formState.errors.items.root.message}</p>
                  )}

                  {/* Invoice-level discount */}
                  <div className="grid grid-cols-2 gap-4 pt-2 border-t">
                  <FormField
                    control={form.control}
                    name="invoiceDiscountPercent"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>خصم الفاتورة %</FormLabel>
                        <FormControl>
                          <Input
                            type="text"
                            lang="en"
                            dir="ltr"
                            inputMode="decimal"
                            className="font-mono"
                            placeholder="0.00"
                            key={`invDiscPct-${formatDecimal(Number(field.value||0),2)}`}
                            defaultValue={formatDecimal(Number(field.value||0), 2)}
                            onBlur={(e) => {
                              commitHeaderNumber('invoiceDiscountPercent', e.target.value, { min: 0, max: 100, fallback: 0 });
                              form.setValue('invoiceDiscountAmount', 0, { shouldDirty: true, shouldValidate: false });
                              setHeaderDrafts((prev) => {
                                if (!('invoiceDiscountAmount' in prev)) return prev;
                                const out = { ...prev };
                                delete out.invoiceDiscountAmount;
                                return out;
                              });
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="invoiceDiscountAmount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>مبلغ الخصم</FormLabel>
                        <FormControl>
                          <Input
                            type="text"
                            lang="en"
                            dir="ltr"
                            inputMode="decimal"
                            className="font-mono"
                            placeholder="0.00"
                            key={`invDiscAmt-${formatDecimal(Number(field.value||0),2)}`}
                            defaultValue={formatDecimal(Number(field.value||0), 2)}
                            onBlur={(e) => {
                              commitHeaderNumber('invoiceDiscountAmount', e.target.value, { min: 0, fallback: 0 });
                              form.setValue('invoiceDiscountPercent', 0, { shouldDirty: true, shouldValidate: false });
                              setHeaderDrafts((prev) => {
                                if (!('invoiceDiscountPercent' in prev)) return prev;
                                const out = { ...prev };
                                delete out.invoiceDiscountPercent;
                                return out;
                              });
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                </div>
              </TabsContent>

              {realEstateEnabled && (
                <TabsContent value="real-estate" className="mt-4 space-y-4">
                  <div className={`rounded-lg border p-4 space-y-4 ${isRealEstateSaleMode ? 'border-emerald-200 bg-emerald-50/40' : 'border-dashed bg-muted/10'}`}>
                    <div className="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
                      <div>
                        <p className="text-sm font-medium">بيع عقاري</p>
                        <p className="text-xs text-muted-foreground">
                          {isRealEstateSaleMode
                            ? 'تم ربط الوحدة العقارية بنجاح. يمكن رؤية التفاصيل في الملخص أدناه.'
                            : 'اختر مشروعاً عقارياً ووحدة من السطور أدناه لإضافة بيانات العقار إلى الفاتورة.'}
                        </p>
                      </div>
                      {isRealEstateSaleMode && (
                        <div className="rounded-md border bg-background px-3 py-1.5 text-xs text-muted-foreground">
                          {selectedRealEstateProject?.name || primaryRealEstateLink?.projectName || '�'}
                          {' / '}
                          {selectedRealEstateUnit?.name || selectedRealEstateUnit?.unitCode || primaryRealEstateLink?.unitName || '�'}
                        </div>
                      )}
                    </div>

                    <div className="rounded-md border border-dashed bg-background/70 px-3 py-2 text-xs text-muted-foreground">
                      في هذا الوضع <span className="font-medium">المخزون / الحسابات / الأقساط</span> مرتبطة تلقائياً بالوحدة المحددة بشكل كامل.
                    </div>

                    {String(watchedRealEstateUnitId || '').trim() && (
                      <div className="rounded-lg border bg-background/80 p-3 space-y-3">
                        <div className="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
                          <div>
                            <p className="text-sm font-medium">تفاصيل الوحدة العقارية المحددة</p>
                            <p className="text-xs text-muted-foreground">يتم تعبئة هذه البيانات من بيانات المشروع العقاري تلقائياً بناءً على الوحدة.</p>
                          </div>
                          {selectedRealEstateUsageLabel && (
                            <span className="rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-foreground/80">
                              {selectedRealEstateUsageLabel}
                            </span>
                          )}
                        </div>

                        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">الطابق / الدور</div>
                            <div className="mt-1 text-sm font-medium">{selectedRealEstateFloorDetail?.floorLabel || selectedRealEstateUnit?.floor || '—'}</div>
                          </div>
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">الوحدة</div>
                            <div className="mt-1 text-sm font-medium">{selectedRealEstateEngineeringUnitDetail?.unitLabel || selectedRealEstateUnit?.name || selectedRealEstateUnit?.unitCode || '—'}</div>
                          </div>
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">المساحة</div>
                            <div className="mt-1 font-mono text-base" dir="ltr">{formatDecimal(Number(selectedRealEstateEngineeringUnitDetail?.area || selectedRealEstateUnit?.area || 0), 2)} م²</div>
                          </div>
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">قيمة التقدير / السعر</div>
                            <div className="mt-1 font-mono text-base" dir="ltr">{formatDecimal(realEstateContractValuePreview, 2)}</div>
                          </div>
                        </div>

                        {(selectedRealEstateFloorDetail?.description || selectedRealEstateFloorDetail?.notes || selectedRealEstateEngineeringUnitDetail?.notes || selectedRealEstateProject?.designSummary) && (
                          <div className="grid gap-3 md:grid-cols-2">
                            <div className="rounded-lg border bg-muted/10 p-3">
                              <div className="text-[11px] text-muted-foreground">وصف الطابق</div>
                              <div className="mt-1 text-sm">{selectedRealEstateFloorDetail?.description || selectedRealEstateProject?.designSummary || 'لا يوجد وصف للطابق.'}</div>
                            </div>
                            <div className="rounded-lg border bg-muted/10 p-3">
                              <div className="text-[11px] text-muted-foreground">ملاحظات الطابق / الوحدة</div>
                              <div className="mt-1 text-sm">{selectedRealEstateEngineeringUnitDetail?.notes || selectedRealEstateFloorDetail?.notes || selectedRealEstateUnit?.notes || 'لا توجد ملاحظات.'}</div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    {String(watchedRealEstateUnitId || '').trim() && !selectedRealEstateMaterial && (
                      <div className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900">
                        هذه الوحدة لا تملك صنفاً مربوطاً. يمكن تحديد الصنف والسعر يدوياً للفاتورة الحالية.
                      </div>
                    )}

                    {!isRealEstateSaleMode ? (
                      <div className="rounded-md border border-dashed bg-background/60 px-3 py-2 text-xs text-muted-foreground">
                        عند اختيار وحدة عقارية تظهر التفاصيل هنا. لم يتم اختيار أي وحدة حتى الآن لهذه الفاتورة.
                      </div>
                    ) : (
                      <>
                        {hasMixedRealEstateLinks && (
                          <div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">
                            تحتوي بعض البنود على وحدات عقارية مختلفة. في فاتورة عقارية يجب أن تكون جميع البنود لنفس الوحدة فقط.
                          </div>
                        )}
                        {hasUnlinkedItemsInRealEstateMode && !hasMixedRealEstateLinks && (
                          <div className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900">
                            بعض الأصناف غير مرتبطة بالوحدة. يرجى التأكد من أن جميع البنود مرتبطة بنفس الوحدة في هذه الفاتورة.
                          </div>
                        )}

                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">

                          <FormField
                            control={form.control}
                            name="realEstateContractNumber"
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>رقم العقد</FormLabel>
                                <FormControl>
                                  <Input {...field} placeholder="اختياري" />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />

                          <FormField
                            control={form.control}
                            name="realEstateContractDate"
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>تاريخ العقد</FormLabel>
                                <FormControl>
                                  <Input type="date" {...field} value={field.value ?? ''} />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />

                          <FormField
                            control={form.control}
                            name="realEstateHandoverDate"
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>تاريخ التسليم</FormLabel>
                                <FormControl>
                                  <Input type="date" {...field} value={field.value ?? ''} />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />

                          <FormField
                            control={form.control}
                            name="realEstateContractValue"
                            render={() => (
                              <FormItem>
                                <FormLabel>قيمة العقد</FormLabel>
                                <FormControl>
                                  <Input
                                    type="text"
                                    lang="en"
                                    dir="ltr"
                                    inputMode="decimal"
                                    className="font-mono"
                                    placeholder="0.00"
                                    key={`reContractVal-${formatDecimal(numericWatchedRealEstateContractValue,2)}`}
                                    defaultValue={formatDecimal(numericWatchedRealEstateContractValue, 2)}
                                    onBlur={(event) => commitHeaderNumber('realEstateContractValue', event.target.value, { min: 0, fallback: 0 })}
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />

                          <FormField
                            control={form.control}
                            name="realEstateInstallmentMode"
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>نمط الأقساط</FormLabel>
                                <Select value={field.value || 'existing'} onValueChange={field.onChange}>
                                  <FormControl>
                                    <SelectTrigger>
                                      <SelectValue placeholder="اختر نمط الأقساط" />
                                    </SelectTrigger>
                                  </FormControl>
                                  <SelectContent>
                                    <SelectItem value="existing">الأقساط وفق الجدول المدخل</SelectItem>
                                    <SelectItem value="auto">توليد أقساط تلقائياً</SelectItem>
                                  </SelectContent>
                                </Select>
                                <FormMessage />
                              </FormItem>
                            )}
                          />

                          {watchedRealEstateInstallmentMode === 'auto' && (
                            <>
                              <FormField
                                control={form.control}
                                name="realEstateInstallmentCount"
                                render={({ field }) => (
                                  <FormItem>
                                    <FormLabel>عدد الأقساط</FormLabel>
                                    <FormControl>
                                      <Input
                                        type="number"
                                        min="1"
                                        step="1"
                                        {...field}
                                        value={field.value ?? 0}
                                        onChange={(event) => field.onChange(Number(event.target.value || 0))}
                                      />
                                    </FormControl>
                                    <FormMessage />
                                  </FormItem>
                                )}
                              />

                              <FormField
                                control={form.control}
                                name="realEstateFirstDueDate"
                                render={({ field }) => (
                                  <FormItem>
                                    <FormLabel>تاريخ أول قسط</FormLabel>
                                    <FormControl>
                                      <Input type="date" {...field} value={field.value ?? ''} />
                                    </FormControl>
                                    <FormMessage />
                                  </FormItem>
                                )}
                              />

                              <FormField
                                control={form.control}
                                name="realEstateInstallmentInterval"
                                render={({ field }) => (
                                  <FormItem>
                                    <FormLabel>دورية القسط</FormLabel>
                                    <Select value={field.value || 'monthly'} onValueChange={field.onChange}>
                                      <FormControl>
                                        <SelectTrigger>
                                          <SelectValue placeholder="اختر الدورية" />
                                        </SelectTrigger>
                                      </FormControl>
                                      <SelectContent>
                                        <SelectItem value="monthly">شهري</SelectItem>
                                        <SelectItem value="quarterly">ربع سنوي</SelectItem>
                                      </SelectContent>
                                    </Select>
                                    <FormMessage />
                                  </FormItem>
                                )}
                              />
                            </>
                          )}
                        </div>

                        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">قيمة العقد</div>
                            <div className="mt-1 font-mono text-base" dir="ltr">{realEstateContractValuePreview.toFixed(2)}</div>
                          </div>
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">مقدم مدفوع</div>
                            <div className="mt-1 font-mono text-base text-emerald-700" dir="ltr">{amountReceived.toFixed(2)}</div>
                          </div>
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">الرصيد المؤجل</div>
                            <div className="mt-1 font-mono text-base text-amber-700" dir="ltr">{realEstateDeferredAmountPreview.toFixed(2)}</div>
                          </div>
                          <div className="rounded-lg border bg-background p-3">
                            <div className="text-[11px] text-muted-foreground">الأقساط</div>
                            <div className="mt-1 text-sm font-medium">
                              {watchedRealEstateInstallmentMode === 'auto'
                                ? `${Number(form.getValues('realEstateInstallmentCount') || 0)} قسط تلقائي`
                                : `${existingInstallmentCount} قسط يدوي`}
                            </div>
                          </div>
                        </div>
                      </>
                    )}
                  </div>
                </TabsContent>
              )}

              {/* -- Payment Tab -- */}
              <TabsContent value="payment" className="mt-4 space-y-5">
                <div className="rounded-xl border bg-card p-5 space-y-5">
                  <div className="flex flex-col gap-1 border-b pb-4 md:flex-row md:items-center md:justify-between">
                    <div>
                      <div className="text-base font-semibold">تفاصيل الدفع</div>
                      <p className="text-xs text-muted-foreground">حدد طرق السداد ثم وزّع المبالغ على كل طريقة بشكل صحيح.</p>
                    </div>
                    <div className="text-xs text-muted-foreground">إجمالي الفاتورة: <span className="font-mono" dir="ltr">{grandTotal.toFixed(2)}</span></div>
                  </div>

                  <FormField
                    control={form.control}
                    name="paymentMethodsSelected"
                    render={({ field }) => (
                      <FormItem className="rounded-lg border bg-muted/30 p-4">
                        <FormLabel>طرق الدفع</FormLabel>
                        <div className="mt-2 flex flex-wrap gap-2">
                          {[
                            { value: 'cash' as const, label: 'نقدي' },
                            { value: 'check' as const, label: 'شيك' },
                            { value: 'credit' as const, label: 'آجل (دين)' },
                          ].map((option) => {
                            const values = Array.isArray(field.value) ? field.value : [];
                            const active = values.includes(option.value);
                            return (
                              <Button
                                key={option.value}
                                type="button"
                                variant={active ? 'default' : 'outline'}
                                size="sm"
                                className={active ? 'shadow-sm' : ''}
                                onClick={() => {
                                  const nextValues = active
                                    ? values.filter((value) => value !== option.value)
                                    : [...values, option.value];
                                  field.onChange(nextValues);
                                }}
                              >
                                {option.label}
                              </Button>
                            );
                          })}
                        </div>
                        <p className="mt-2 text-xs text-muted-foreground">يمكن اختيار أكثر من طريقة في نفس الفاتورة.</p>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {isRealEstateSaleMode && (
                    <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900">
                      <div className="font-medium">ملخص عقد البيع العقاري</div>
                      <div className="mt-1">
                        قيمة العقد <span className="font-mono" dir="ltr">{realEstateContractValuePreview.toFixed(2)}</span>
                        {' - '}دفعة أولى <span className="font-mono" dir="ltr">{amountReceived.toFixed(2)}</span>
                        {' - '}المتبقي <span className="font-mono" dir="ltr">{realEstateDeferredAmountPreview.toFixed(2)}</span>
                        {' - '}{watchedRealEstateInstallmentMode === 'auto' ? 'سيتم توليد جدول الأقساط تلقائياً بعد الحفظ.' : 'يمكن تعديل جدول الأقساط يدوياً لاحقاً.'}
                      </div>
                    </div>
                  )}

                  <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <div className="rounded-lg border bg-background p-3">
                      <div className="text-[11px] text-muted-foreground">المدفوع نقداً</div>
                      <div className="mt-1 font-mono text-base" dir="ltr">{amountReceived.toFixed(2)}</div>
                    </div>
                    <div className="rounded-lg border bg-background p-3">
                      <div className="text-[11px] text-muted-foreground">المدفوع بالشيكات</div>
                      <div className="mt-1 font-mono text-base" dir="ltr">{paymentChecksTotal.toFixed(2)}</div>
                    </div>
                    <div className="rounded-lg border bg-background p-3">
                      <div className="text-[11px] text-muted-foreground">الرصيد الآجل</div>
                      <div className="mt-1 font-mono text-base" dir="ltr">{creditAmount.toFixed(2)}</div>
                    </div>
                    <div className="rounded-lg border bg-background p-3">
                      <div className="text-[11px] text-muted-foreground">المتبقي</div>
                      <div className={`mt-1 font-mono text-base ${amountDue > 0 ? 'text-red-600' : 'text-emerald-600'}`} dir="ltr">{amountDue.toFixed(2)}</div>
                    </div>
                  </div>

                  {isCashSelected && (
                    <div className="rounded-lg border bg-background p-4">
                      <FormField
                        control={form.control}
                        name="cashAmount"
                        render={({ field }) => (
                          <FormItem className="max-w-md">
                            <FormLabel>المبلغ النقدي</FormLabel>
                            <FormControl>
                              <Input
                                type="text"
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                className="font-mono"
                                key={`cashAmt-${formatDecimal(Number(field.value||0),2)}`}
                                defaultValue={formatDecimal(Number(field.value||0), 2)}
                                onBlur={(e) => commitHeaderNumber('cashAmount', e.target.value, { min: 0, fallback: 0 })}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                  )}

                  {isCheckSelected && (
                    <div className="rounded-lg border bg-sky-50/70 p-4 space-y-4">
                      {mode === 'edit' && (
                        <div className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900">
                          تنبيه مهم: عند تعديل بيانات الشيكات الحالية سيتم تحديث الحركات المرتبطة بها. راجع الحالة والمبالغ قبل الحفظ النهائي.
                        </div>
                      )}
                      <div className="flex flex-col gap-3 border-b border-sky-100 pb-3 md:flex-row md:items-center md:justify-between">
                        <div>
                          <div className="text-sm font-semibold text-sky-950">تفاصيل الشيكات</div>
                          <p className="text-xs text-sky-800/80">أدخل بيانات كل شيك بدقة ثم حدّد حالته لمتابعة التسوية لاحقًا.</p>
                        </div>
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => appendPaymentCheck(emptyPaymentCheck(watchedCurrencyCode))}
                        >
                          <PlusCircle className="me-2 h-4 w-4" />
                          إضافة شيك
                        </Button>
                      </div>

                      <div className="overflow-x-auto rounded-md border bg-background">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>رقم الشيك</TableHead>
                              <TableHead>تاريخ الشيك</TableHead>
                              <TableHead>البنك</TableHead>
                              <TableHead>اسم البنك</TableHead>
                              <TableHead className="text-right">المبلغ</TableHead>
                              <TableHead>العملة</TableHead>
                              <TableHead>المرجع</TableHead>
                              {mode === 'edit' && <TableHead>الحالة</TableHead>}
                              <TableHead className="text-right">إجراء</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {paymentCheckFields.map((paymentCheckField, index) => (
                              <TableRow key={paymentCheckField.id}>
                                <TableCell className="min-w-[150px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.checkNumber`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <FormControl>
                                          <Input
                                            placeholder="رقم الشيك"
                                            {...field}
                                            ref={(node) => {
                                              field.ref(node);
                                              setPaymentCheckCellRef(index, 0, node);
                                            }}
                                            onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 0)}
                                          />
                                        </FormControl>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                <TableCell className="min-w-[140px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.checkDate`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <FormControl>
                                          <Input
                                            type="date"
                                            {...field}
                                            ref={(node) => {
                                              field.ref(node);
                                              setPaymentCheckCellRef(index, 1, node);
                                            }}
                                            onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 1)}
                                          />
                                        </FormControl>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                <TableCell className="min-w-[150px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.bankId`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <Popover
                                          open={Boolean(paymentCheckBankOpenByRow[index])}
                                          onOpenChange={(open) => {
                                            setPaymentCheckBankOpenByRow((prev) => ({ ...prev, [index]: open }));
                                            if (!open) {
                                              setPaymentCheckBankQueryByRow((prev) => ({ ...prev, [index]: '' }));
                                            }
                                          }}
                                        >
                                          <PopoverTrigger asChild>
                                            <FormControl>
                                              <Button
                                                type="button"
                                                variant="outline"
                                                role="combobox"
                                                className={cn('w-full justify-between', !(field.value || '').trim() && 'text-muted-foreground')}
                                                ref={(node) => setPaymentCheckCellRef(index, 2, node)}
                                                onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 2)}
                                              >
                                                {(() => {
                                                  const selectedBank = bankOptions.find((bank) => String(bank.id || '').trim() === String(field.value || '').trim());
                                                  return selectedBank
                                                    ? String(selectedBank.name || (selectedBank as any).fullName || selectedBank.nameEn || selectedBank.code || selectedBank.id)
                                                    : 'اختر بنكًا';
                                                })()}
                                                <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                                              </Button>
                                            </FormControl>
                                          </PopoverTrigger>
                                          <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                                            <div className="p-2 border-b">
                                              <Input
                                                placeholder="ابحث باسم البنك أو الرمز..."
                                                value={paymentCheckBankQueryByRow[index] || ''}
                                                onChange={(event) => {
                                                  const nextValue = event.target.value;
                                                  setPaymentCheckBankQueryByRow((prev) => ({ ...prev, [index]: nextValue }));
                                                }}
                                                autoFocus
                                              />
                                            </div>
                                            <div className="max-h-60 overflow-y-auto">
                                              {bankOptions
                                                .filter((bank) => {
                                                  const query = String(paymentCheckBankQueryByRow[index] || '').trim().toLowerCase();
                                                  if (!query) return true;
                                                  const haystack = [
                                                    String(bank.name || ''),
                                                    String((bank as any).nameEn || ''),
                                                    String((bank as any).fullName || ''),
                                                    String(bank.code || ''),
                                                    String((bank as any).branch || ''),
                                                  ].join(' ').toLowerCase();
                                                  return haystack.includes(query);
                                                })
                                                .map((bank) => {
                                                  const selected = String(bank.id || '').trim() === String(field.value || '').trim();
                                                  const primaryName = String(bank.name || (bank as any).fullName || bank.nameEn || bank.code || bank.id);
                                                  return (
                                                    <button
                                                      key={bank.id}
                                                      type="button"
                                                      className={cn('w-full flex items-center gap-2 text-start px-2 py-1.5 text-sm hover:bg-accent', selected && 'bg-accent')}
                                                      onClick={() => {
                                                        field.onChange(bank.id);
                                                        form.setValue(
                                                          `paymentChecks.${index}.bankName`,
                                                          primaryName,
                                                          { shouldDirty: true, shouldValidate: true }
                                                        );
                                                        setPaymentCheckBankOpenByRow((prev) => ({ ...prev, [index]: false }));
                                                        setPaymentCheckBankQueryByRow((prev) => ({ ...prev, [index]: '' }));
                                                      }}
                                                    >
                                                      <span className={cn('h-2 w-2 rounded-full', selected ? 'bg-primary' : 'bg-transparent')} />
                                                      <span className="flex-1">{primaryName}</span>
                                                      {String(bank.code || '').trim() && (
                                                        <span className="text-xs text-muted-foreground">{bank.code}</span>
                                                      )}
                                                    </button>
                                                  );
                                                })}

                                              <button
                                                type="button"
                                                className="w-full border-t text-start px-2 py-2 text-sm text-primary hover:bg-accent"
                                                onClick={() => {
                                                  setPendingBankRowIndex(index);
                                                  setIsAddBankDialogOpen(true);
                                                  setPaymentCheckBankOpenByRow((prev) => ({ ...prev, [index]: false }));
                                                }}
                                              >
                                                + إضافة بنك جديد
                                              </button>
                                            </div>
                                          </PopoverContent>
                                        </Popover>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                <TableCell className="min-w-[150px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.bankName`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <FormControl>
                                          <Input
                                            placeholder="اسم البنك"
                                            {...field}
                                            ref={(node) => {
                                              field.ref(node);
                                              setPaymentCheckCellRef(index, 3, node);
                                            }}
                                            onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 3)}
                                          />
                                        </FormControl>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                <TableCell className="min-w-[130px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.amount`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <FormControl>
                                          <Input
                                            type="text"
                                            lang="en"
                                            dir="ltr"
                                            inputMode="decimal"
                                            className="font-mono text-right"
                                            placeholder="0.00"
                                            {...field}
                                            ref={(node) => {
                                              field.ref(node);
                                              setPaymentCheckCellRef(index, 4, node);
                                            }}
                                            onFocus={(event) => {
                                              event.target.select();
                                            }}
                                            onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 4)}
                                          />
                                        </FormControl>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                <TableCell className="min-w-[130px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.currency`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <Select value={field.value ?? watchedCurrencyCode} onValueChange={field.onChange}>
                                          <FormControl>
                                            <SelectTrigger
                                              ref={(node) => setPaymentCheckCellRef(index, 5, node)}
                                              onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 5)}
                                            >
                                              <SelectValue placeholder="العملة" />
                                            </SelectTrigger>
                                          </FormControl>
                                          <SelectContent>
                                            {currencies.map((currency) => (
                                              <SelectItem key={currency.code} value={currency.code}>{currency.code}</SelectItem>
                                            ))}
                                          </SelectContent>
                                        </Select>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                <TableCell className="min-w-[160px] align-top">
                                  <FormField
                                    control={form.control}
                                    name={`paymentChecks.${index}.reference`}
                                    render={({ field }) => (
                                      <FormItem>
                                        <FormControl>
                                          <Input
                                            placeholder="مرجع / ملاحظة"
                                            {...field}
                                            ref={(node) => {
                                              field.ref(node);
                                              setPaymentCheckCellRef(index, 6, node);
                                            }}
                                            onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 6)}
                                          />
                                        </FormControl>
                                        <FormMessage />
                                      </FormItem>
                                    )}
                                  />
                                </TableCell>
                                {mode === 'edit' && (
                                  <TableCell className="min-w-[140px] align-top">
                                    <FormField
                                      control={form.control}
                                      name={`paymentChecks.${index}.status`}
                                      render={({ field }) => (
                                        <FormItem>
                                          <Select value={field.value ?? 'pending'} onValueChange={field.onChange}>
                                            <FormControl>
                                              <SelectTrigger
                                                ref={(node) => setPaymentCheckCellRef(index, 7, node)}
                                                onKeyDown={(event) => handlePaymentCheckGridKeyDown(event, index, 7)}
                                              >
                                                <SelectValue />
                                              </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                              <SelectItem value="pending">قيد التحصيل</SelectItem>
                                              <SelectItem value="cleared">تم التحصيل</SelectItem>
                                              <SelectItem value="rejected">مرفوض</SelectItem>
                                              <SelectItem value="returned">مرتجع</SelectItem>
                                            </SelectContent>
                                          </Select>
                                          <FormMessage />
                                        </FormItem>
                                      )}
                                    />
                                  </TableCell>
                                )}
                                <TableCell className="w-[80px] align-top text-right">
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => removePaymentCheck(index)}
                                    disabled={paymentCheckFields.length === 1}
                                  >
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>

                      <div className="flex items-center justify-between text-xs text-sky-900">
                        <span>عدد الشيكات: {paymentCheckFields.length}</span>
                        <span>إجمالي الشيكات: <span className="font-mono" dir="ltr">{paymentChecksTotal.toFixed(2)}</span></span>
                      </div>
                      {form.formState.errors.paymentChecks?.message && (
                        <p className="text-sm text-destructive">{String(form.formState.errors.paymentChecks.message)}</p>
                      )}
                    </div>
                  )}

                  {isCreditSelected && (
                    <div className="rounded-lg border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
                      <div className="flex items-center justify-between">
                        <span className="font-medium">رصيد آجل (دين)</span>
                        <span className="font-mono text-base" dir="ltr">{creditAmount.toFixed(2)}</span>
                      </div>
                      <p className="mt-2 text-xs text-amber-800">سيتم تسجيل هذا المبلغ كذمة على العميل بعد اعتماد الفاتورة.</p>
                    </div>
                  )}
                </div>
              </TabsContent>

              {/* -- Notes Tab -- */}
              <TabsContent value="notes" className="space-y-4 mt-4">
                <FormField
                  control={form.control}
                  name="customerNotes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>ملاحظات العميل</FormLabel>
                      <FormControl>
                        <Textarea rows={3} placeholder="اكتب أي ملاحظات للعميل" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="internalNotes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>ملاحظات داخلية</FormLabel>
                      <FormControl>
                        <Textarea rows={3} placeholder="ملاحظات داخلية فقط" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </TabsContent>

              <TabsContent value="log" className="mt-4 space-y-4">
                <div className="rounded-lg border bg-card p-4 space-y-4">
                  <div className="flex items-center justify-between border-b pb-3">
                    <div>
                      <div className="text-sm font-semibold">LOG</div>
                      <p className="text-xs text-muted-foreground">سجل العمليات المرتبطة بهذه الفاتورة.</p>
                    </div>
                    {invoiceId && (
                      <div className="text-xs text-muted-foreground">رقم الفاتورة: <span className="font-mono" dir="ltr">{invoiceId}</span></div>
                    )}
                  </div>

                  {activityLogEntries.length > 0 ? (
                    <div className="space-y-3">
                      {activityLogEntries.map((entry: any, index: number) => (
                        <div key={entry.id || `${entry.timestamp || 'log'}-${index}`} className="rounded-lg border bg-muted/20 p-3">
                          <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
                            <div className="space-y-1">
                              <div className="text-sm font-medium">{String(entry.message || entry.action || 'بدون وصف')}</div>
                              <div className="text-xs text-muted-foreground">
                                {String(entry.byName || entry.by || 'غير معروف')}
                                {entry.action ? ` - ${String(entry.action)}` : ''}
                              </div>
                            </div>
                            <div className="text-xs font-mono text-muted-foreground" dir="ltr">{String(entry.timestamp || '')}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground">
                      {mode === 'edit' ? 'لا توجد عمليات مسجلة على هذه الفاتورة حتى الآن.' : 'سيظهر سجل العمليات بعد حفظ الفاتورة.'}
                    </div>
                  )}
                </div>
              </TabsContent>

            </Tabs>

            {/* -- Below Tabs: Tax Method + Summary -- */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-1">
              <FormField
                control={form.control}
                name="taxMethod"
                render={({ field }) => (
                  <FormItem>
                    <div className="h-full space-y-3 border-b pb-3">
                      <div>
                        <div className="text-sm font-semibold">طريقة الضريبة</div>
                        <p className="text-xs text-muted-foreground">اختر طريقة احتساب الضريبة حسب سياسة الفاتورة لهذه العملية.</p>
                      </div>

                      <div className="flex flex-wrap gap-x-5 gap-y-3">
                        {[
                          { value: 'line-level', label: 'ضريبة لكل بند' },
                          { value: 'invoice-level', label: 'ضريبة على الفاتورة' },
                          { value: 'tax-inclusive', label: 'سعر شامل الضريبة' },
                          { value: 'tax-exempt', label: 'معفى من الضريبة' },
                        ].map((opt) => (
                          <div key={opt.value} className="flex items-center gap-2 whitespace-nowrap">
                            <input
                              id={`tax-method-${opt.value}`}
                              type="radio"
                              className="w-4 h-4 cursor-pointer"
                              value={opt.value}
                              checked={(field.value ?? normalizedDefaultTaxMethod) === opt.value}
                              onChange={() => field.onChange(opt.value)}
                            />
                            <label htmlFor={`tax-method-${opt.value}`} className="cursor-pointer text-sm">
                              {opt.label}
                            </label>
                          </div>
                        ))}
                      </div>

                        {watchedTaxMethod === 'tax-exempt' && (
                          <div className="rounded-md border border-amber-300 bg-amber-50 p-3 space-y-3">
                            <div className="text-xs text-amber-900">تم اختيار الإعفاء الضريبي. يرجى تعبئة سبب الإعفاء والمرجع.</div>
                            <FormField
                              control={form.control}
                              name="taxExemptionReason"
                              render={({ field: reasonField }) => (
                                <FormItem>
                                  <FormLabel>سبب الإعفاء الضريبي</FormLabel>
                                  <FormControl>
                                    <Input placeholder="مثال: تصدير / جهة حكومية / إعفاء خاص" {...reasonField} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                            <FormField
                              control={form.control}
                              name="taxExemptionReference"
                              render={({ field: refField }) => (
                                <FormItem>
                                  <FormLabel>مرجع الإعفاء / رقم المستند</FormLabel>
                                  <FormControl>
                                    <Input placeholder="مثال: قرار إعفاء أو رقم كتاب رسمي" {...refField} />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          </div>
                        )}
                    </div>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="space-y-2 border-b pb-3 text-sm">
                <div className="text-sm font-semibold">ملخص الفاتورة</div>
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground">إجمالي البنود</span>
                  <span className="font-medium font-mono" dir="ltr">{subTotal.toFixed(2)}</span>
                </div>
                {campaignPreviewTotal > 0 && (
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">خصم الحملات (تقديري)</span>
                    <span className="font-medium font-mono text-emerald-700" dir="ltr">-{campaignPreviewTotal.toFixed(2)}</span>
                  </div>
                )}
                {invDisc > 0 && (
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">خصم الفاتورة</span>
                    <span className="font-medium font-mono text-red-600" dir="ltr">-{invDisc.toFixed(2)}</span>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground">الضريبة</span>
                  <span className="font-medium font-mono" dir="ltr">{taxTotal.toFixed(2)}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground">الإجمالي</span>
                  <span className="font-medium font-mono" dir="ltr">{grandTotal.toFixed(2)}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-muted-foreground">المدفوع</span>
                  <span className="font-medium font-mono" dir="ltr">{(amountReceived as number).toFixed(2)}</span>
                </div>
                {String(watchedSecondaryCustomerId || '').trim() && normalizedSecondaryCoveragePercent > 0 && (
                  <>
                    <div className="border-t pt-2 flex items-center justify-between">
                      <span className="text-muted-foreground">حصة العميل الرئيسي</span>
                      <span className="font-medium font-mono" dir="ltr">
                        {((Number(grandTotal || 0) * primaryCoveragePercent) / 100).toFixed(2)} {watchedCurrencyCode || ''}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-muted-foreground">حصة العميل الثانوي</span>
                      <span className="font-medium font-mono" dir="ltr">
                        {((Number(grandTotal || 0) * normalizedSecondaryCoveragePercent) / 100).toFixed(2)} {watchedCurrencyCode || ''}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-muted-foreground">حصة العميل الثانوي (عملة الأساس)</span>
                      <span className="font-medium font-mono" dir="ltr">
                        {(((Number(grandTotal || 0) * normalizedSecondaryCoveragePercent) / 100) * (Number(watchedExchangeRate || 1) || 1)).toFixed(2)}
                      </span>
                    </div>
                  </>
                )}
                <div className="border-t pt-2 flex items-center justify-between">
                  <span className="font-semibold">المتبقي</span>
                  <span className="text-base font-bold font-mono" dir="ltr">{amountDue.toFixed(2)}</span>
                </div>
              </div>
            </div>

            {/* -- Actions -- */}
            <div className="flex gap-4 pt-2">
              <Popover open={columnSettingsOpen} onOpenChange={setColumnSettingsOpen}>
                <PopoverTrigger asChild>
                  <Button type="button" variant="outline">
                    <Settings className="me-2 h-4 w-4" />
                    {'إعدادات العرض'}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[320px]">
                  <div className="space-y-3">
                    <div>
                      <div className="text-sm font-medium">{'إعدادات العرض'}</div>
                      <p className="mt-1 text-xs text-muted-foreground">{'غيّر طريقة عرض بعض الأعمدة كما يناسب نمط عملك.'}</p>
                    </div>
                    <label className="flex items-start justify-between gap-3 rounded border p-3 text-sm">
                      <div className="space-y-1">
                        <div>{'طريقة عرض الوحدة'}</div>
                        <div className="text-xs text-muted-foreground">{'حدد ما إذا كانت الوحدة تُعرض بالوصف أو بالرمز أو بكليهما.'}</div>
                      </div>
                      <Select value={unitDisplayMode} onValueChange={(value) => setUnitDisplayMode(value as UnitDisplayMode)}>
                        <FormControl>
                          <SelectTrigger className="w-[140px]">
                            <SelectValue placeholder={'اختر الوضع'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="description">{'الوصف فقط'}</SelectItem>
                          <SelectItem value="shortCode">{'الرمز فقط'}</SelectItem>
                          <SelectItem value="both">{'الوصف + الرمز'}</SelectItem>
                        </SelectContent>
                      </Select>
                    </label>
                  </div>
                </PopoverContent>
              </Popover>
              <Button type="submit" disabled={isSubmitting || isEditLockedByStatus} className="flex-1">
                {isSubmitting
                  ? 'جارٍ الحفظ...'
                  : isEditLockedByStatus
                    ? 'التعديل غير متاح'
                  : mode === 'edit'
                    ? 'حفظ التعديلات'
                    : 'حفظ الفاتورة'}
              </Button>
              <Button type="button" variant="outline" onClick={() => router.back()}>
                رجوع
              </Button>
            </div>
          </form>

          <Dialog
            open={showItemPicker}
            onOpenChange={(open) => {
              setShowItemPicker(open);
              if (!open) {
                setPickerTargetRowIndex(null);
                setItemPickerQuery('');
                if (itemPickerInputRef.current) {
                  itemPickerInputRef.current.value = '';
                }
              }
            }}
          >
            <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-7xl">
              <DialogHeader>
                <DialogTitle>{realEstateEnabled ? 'اختيار صنف/وحدة' : 'اختيار صنف'}</DialogTitle>
                <DialogDescription>
                  {realEstateEnabled
                    ? 'اختر الصنف المطلوب أو وحدة عقارية لإضافتها كسطر جديد.'
                    : 'ابحث عن صنف ثم أضفه إلى الفاتورة.'}
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-4">
                <Input
                  ref={itemPickerInputRef}
                  placeholder={realEstateEnabled ? 'ابحث في الأصناف أو الوحدات العقارية...' : 'ابحث عن صنف...'}
                  defaultValue=""
                  onBlur={(e) => setItemPickerQuery(e.currentTarget.value.trim())}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      setItemPickerQuery(e.currentTarget.value.trim());
                    }
                  }}
                  autoFocus
                />
                <div className="flex flex-wrap items-center justify-end gap-2">
                  {!realEstateEnabled && (
                    <Button
                      type="button"
                      variant={showAvailableOnlyInPicker ? 'default' : 'outline'}
                      size="sm"
                      onClick={() => setShowAvailableOnlyInPicker((prev) => !prev)}
                    >
                      <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
                        {showAvailableOnlyInPicker ? 'إظهار كل الأصناف' : 'إظهار الرصيد + المتوفر فقط'}
                      </span>
                    </Button>
                  )}
                  <button
                    className="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-9 rounded-md px-3"
                    type="button"
                    onClick={() => router.push(realEstateEnabled ? '/admin/data/real-estate' : '/admin/data/materials')}
                  >
                    <PlusCircle className="h-4 w-4 me-2" />
                    {realEstateEnabled ? 'إضافة وحدة/صنف جديد' : 'إضافة صنف جديد'}
                  </button>
                </div>

                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      {realEstateEnabled ? (
                        <TableRow>
                          <TableHead>الوحدة</TableHead>
                          <TableHead>الكود</TableHead>
                          <TableHead>الدور</TableHead>
                          <TableHead>الحالة</TableHead>
                          <TableHead>الصنف المربوط</TableHead>
                          <TableHead className="text-right">السعر</TableHead>
                        </TableRow>
                      ) : (
                        <TableRow>
                          <TableHead>الصنف</TableHead>
                          <TableHead>رقم الصنف</TableHead>
                          <TableHead>رمز وحدة الصنف</TableHead>
                          <TableHead>الباركود</TableHead>
                          <TableHead className="text-right">السعر</TableHead>
                        </TableRow>
                      )}
                    </TableHeader>
                    <TableBody>
                      {realEstateEnabled ? (
                        filteredPickerUnits.map((unit) => (
                          <TableRow
                            key={unit.id}
                            className="cursor-pointer"
                            onClick={() => handleAddRealEstateUnitFromPicker(unit)}
                          >
                            <TableCell className="font-medium">
                              <div className="flex flex-col gap-0.5">
                                <span>{unit.name || unit.unitCode || unit.id}</span>
                                <span className="text-[11px] text-muted-foreground">{unit.projectName || '—'}</span>
                                {unit.notes && (
                                  <span className="text-[11px] text-muted-foreground line-clamp-2">{unit.notes}</span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="font-mono text-xs">{unit.unitCode || unit.id}</TableCell>
                            <TableCell className="text-xs text-muted-foreground">{unit.floor || '-'}</TableCell>
                            <TableCell className="text-xs">
                              {REAL_ESTATE_UNIT_STATUS_LABELS[String(unit.status || '').trim().toLowerCase()] || '�'}
                            </TableCell>
                            <TableCell className={`text-xs ${unit.linkedMaterial ? 'text-muted-foreground' : 'text-amber-700 font-medium'}`}>
                              {unit.linkedMaterial?.name || 'لا يوجد صنف مربوط'}
                            </TableCell>
                            <TableCell className="text-right font-mono" lang="en" dir="ltr">
                              {formatDecimal(Number(unit.actualSaleValue || unit.saleValue || unit.linkedMaterial?.salePrice || 0), 2)}
                            </TableCell>
                          </TableRow>
                        ))
                      ) : (
                        filteredPickerMaterials.map((material) => (
                          <TableRow
                            key={material.id}
                            className="cursor-pointer"
                            onClick={() => handleAddMaterialFromPicker(material)}
                          >
                            <TableCell className="font-medium">
                              <div className="flex flex-col gap-0.5">
                                <span>{material.name}</span>
                                {getMaterialPrimaryUnitLabel(material) && (
                                  <span className="text-[11px] text-muted-foreground">
                                    {'\u0627لوحدة'}: {getMaterialPrimaryUnitLabel(material)}
                                  </span>
                                )}
                                {realEstateEnabled && (material.realEstateProjectName || material.realEstateUnitName) && (
                                  <span className="text-[11px] text-muted-foreground">
                                    {material.realEstateProjectName || '�'} / {material.realEstateUnitName || '�'}
                                  </span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="font-mono text-xs">{material.itemNumber || material.id}</TableCell>
                            <TableCell className="text-xs text-muted-foreground max-w-[180px] truncate">
                              {(material.itemSymbolName || '').trim() || '-'}
                            </TableCell>
                            <TableCell className="font-mono text-xs">{material.barcode || '-'}</TableCell>
                            <TableCell className="text-right font-mono" lang="en" dir="ltr">
                              {formatDecimal(material.salePrice || 0, 2)}
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                      {realEstateEnabled && filteredPickerUnits.length === 0 && (
                        <TableRow>
                          <TableCell colSpan={6} className="text-center text-muted-foreground h-24">
                            {String(watchedRealEstateProjectId || '').trim()
                              ? 'لا توجد وحدات مطابقة لبحثك الحالي.'
                              : 'حدد مشروعاً أولاً لعرض الوحدات المتاحة.'}                          </TableCell>
                        </TableRow>
                      )}
                      {!realEstateEnabled && filteredPickerMaterials.length === 0 && (
                        <TableRow>
                          <TableCell colSpan={5} className="text-center text-muted-foreground h-24">
                            لا توجد أصناف مطابقة للبحث.
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setShowItemPicker(false)}>
                  إلغاء
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          <Dialog
            open={showLossDialog}
            onOpenChange={(open) => {
              setShowLossDialog(open);
              if (!open) {
                setPendingLossPayload(null);
              }
            }}
          >
            <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-3xl">
              <DialogHeader>
                <DialogTitle>تحذير: بيع بأقل من سعر التكلفة</DialogTitle>
                <DialogDescription>
                  {blockSalesBelowCost
                    ? 'البيع بأقل من سعر التكلفة محظور في هذا النظام. يجب تعديل الأسعار أو مراجعة المدير قبل الحفظ.'
                    : 'بعض الأصناف تُباع بأقل من سعر التكلفة. يمكنك المتابعة أو ضبط الأسعار قبل الحفظ.'}
                </DialogDescription>
              </DialogHeader>

              <div className="rounded-md border overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-right">#</TableHead>
                      <TableHead className="text-right">الصنف</TableHead>
                      <TableHead className="text-right">سعر التكلفة</TableHead>
                      <TableHead className="text-right">عملة التكلفة</TableHead>
                      <TableHead className="text-right">سعر البيع</TableHead>
                      <TableHead className="text-right">عملة البيع</TableHead>
                      <TableHead className="text-right">الكمية</TableHead>
                      <TableHead className="text-right">خسارة/وحدة</TableHead>
                      <TableHead className="text-right">إجمالي الخسارة</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {lossWarnings.map((warning) => (
                      <TableRow key={`${warning.index}-${warning.materialName}`}>
                        <TableCell>{warning.index}</TableCell>
                        <TableCell>{warning.materialName}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end">{formatDecimal(warning.cost, 2)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end text-muted-foreground">{warning.costCurrency}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end">{formatDecimal(warning.unitPrice, 2)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end text-muted-foreground">{warning.saleCurrency}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end">{formatDecimal(warning.quantity, 3)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end text-red-600">{formatDecimal(warning.lossPerUnit, 2)}</TableCell>
                        <TableCell lang="en" dir="ltr" className="font-mono text-end text-red-600">{formatDecimal(warning.lossAmount, 2)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setShowLossDialog(false)}>
                  إلغاء
                </Button>
                {!blockSalesBelowCost && (
                  <Button type="button" onClick={continueSaveWithLossHandling}>
                    المتابعة والحفظ
                  </Button>
                )}
              </DialogFooter>
            </DialogContent>
          </Dialog>

          <Dialog
            open={isAddBankDialogOpen}
            onOpenChange={(open) => {
              setIsAddBankDialogOpen(open);
              if (!open) {
                setPendingBankRowIndex(null);
                resetNewBankDraft();
              }
            }}
          >
            <DialogContent>
              <DialogHeader>
                <DialogTitle>إضافة بنك جديد</DialogTitle>
                <DialogDescription>أدخل بيانات البنك الجديد ليظهر في قائمة البنوك المتاحة.</DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div className="space-y-2">
                  <FormLabel>كود البنك</FormLabel>
                  <Input value={newBankDraft.code} onChange={(event) => setNewBankDraft((prev) => ({ ...prev, code: event.target.value }))} placeholder="مثال: BOJ" />
                </div>
                <div className="space-y-2">
                  <FormLabel>اسم البنك</FormLabel>
                  <Input value={newBankDraft.name} onChange={(event) => setNewBankDraft((prev) => ({ ...prev, name: event.target.value }))} placeholder="اسم البنك بالعربية" />
                </div>
                <div className="space-y-2">
                  <FormLabel>الاسم بالإنجليزية</FormLabel>
                  <Input value={newBankDraft.nameEn} onChange={(event) => setNewBankDraft((prev) => ({ ...prev, nameEn: event.target.value }))} placeholder="Bank name in English" />
                </div>
                <div className="space-y-2">
                  <FormLabel>الفرع</FormLabel>
                  <Input value={newBankDraft.branch} onChange={(event) => setNewBankDraft((prev) => ({ ...prev, branch: event.target.value }))} placeholder="اختياري" />
                </div>
              </div>
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setIsAddBankDialogOpen(false)}>إلغاء</Button>
                <Button type="button" onClick={handleCreateGeneralBank} disabled={isCreatingBank}>{isCreatingBank ? 'جارِي الإضافة...' : 'إضافة البنك'}</Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          <Dialog
            open={showPostingDialog}
            onOpenChange={(open) => {
              setShowPostingDialog(open);
              if (!open) {
                setPendingPostingPayload(null);
              }
            }}
          >
            <DialogContent className="w-[96vw] max-w-[520px]">
              <DialogHeader>
                <DialogTitle>تأكيد حفظ الفاتورة</DialogTitle>
                <DialogDescription>
                    {shipmentWorkflowEnabled && documentType === 'shipment'
                      ? <><span>حدد حالة حفظ الإرسالية.</span> <span className="font-medium">الإرسالية لا تُرحَّل دفتريًا كقيد نهائي هنا، وإنما تنشئ مسودة قيد وتؤثر على المخزون في حالة "محفوظة".</span></>
                      : <><span>حدد حالة حفظ هذه الفاتورة.</span> <span className="font-medium">الفواتير المرحلة تؤثر على المخزون وتنشئ قيود دفترية نهائية عند اختيار "مرحلة".</span></>}
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-3">
                  {[
                  {
                    value: 'draft' as const,
                    label: 'مسودة',
                    description: 'لا تؤثر بعد على المخزون/الحسابات.',
                  },
                  {
                    value: 'saved' as const,
                    label: 'محفوظة',
                      description: shipmentWorkflowEnabled && documentType === 'shipment'
                        ? 'تؤثر على المخزون وتنشئ مسودة قيد محاسبي.'
                        : 'تؤثر على المخزون دون ترحيل دفتري.',
                  },
                    ...(shipmentWorkflowEnabled && documentType === 'shipment'
                      ? []
                      : [{
                          value: 'posted' as const,
                          label: 'مرحلة',
                          description: 'تؤثر على المخزون وتنشئ قيود دفترية نهائية.',
                        }]),
                ].map((option) => (
                  <label
                    key={option.value}
                    className={`flex items-start gap-3 rounded-md border p-3 cursor-pointer transition-colors ${selectedPostingType === option.value ? 'border-primary bg-primary/5' : ''}`}
                  >
                    <input
                      className="mt-1 h-4 w-4"
                      type="radio"
                      name="posting-type"
                      checked={selectedPostingType === option.value}
                      onChange={() => setSelectedPostingType(option.value)}
                    />
                    <div>
                      <div className="font-medium">{option.label}</div>
                      <div className="text-xs text-muted-foreground">{option.description}</div>
                    </div>
                  </label>
                ))}
              </div>

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    setShowPostingDialog(false);
                    setPendingPostingPayload(null);
                  }}
                >
                  إلغاء
                </Button>
                <Button type="button" onClick={confirmPostingAndSave} disabled={isSubmitting}>
                  {isSubmitting
                    ? 'جارِي الحفظ...'
                    : selectedPostingType === 'posted'
                      ? 'ترحيل وحفظ'
                      : shipmentWorkflowEnabled && documentType === 'shipment' && selectedPostingType === 'saved'
                        ? 'حفظ واعتماد الإرسالية'
                        : 'حفظ فقط'}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

        </Form>
      </CardContent>
    </Card>
  );
}



