'use client';

import { Fragment, useCallback, useState, useEffect, useMemo, useRef, useTransition, type KeyboardEvent } from 'react';
import { useForm, useFieldArray, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { format } from 'date-fns';
import { useRouter, useSearchParams } from 'next/navigation';
import { formatDateStable } from '@/lib/formatters';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Loader2, PlusCircle, Trash2, ChevronsUpDown, ChevronDown, ChevronUp, Paperclip, FileText, SlidersHorizontal, X } from 'lucide-react';
import { type Supplier, type ProductionItem, type Customer, type ItemGroup, type CustomerCategory, type Warehouse, type MaterialStockReport, type PurchaseOrder, type PurchaseOrderItem, type PurchaseOrderDocument, type Currency, type IncomingCheck, type ChartOfAccount, type Bank, type RealEstateProject } from '@/lib/types';
import { useToast } from '@/hooks/use-toast';
import { handleAcquirePurchaseOrderLock, handleCreatePurchaseOrder, handleReleasePurchaseOrderLock, handleUpdatePurchaseOrder, getUnlinkedPurchaseShipmentsBySupplier, handleCreateWorkTaskFromPurchaseOrder } from '@/lib/actions';
import { PartySelector } from '@/components/invoice-shared';
import { cn } from '@/lib/utils';
import AddSupplierDialog from './add-supplier-dialog';
import { formatCurrency } from '@/lib/currency-formatter';
import { MaterialItemDialog } from '@/components/admin/list-manager';
import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { InvoiceTabsNav } from '@/components/invoice-shared';

function isEffectivelyEmptyPurchaseItem(item: {
  materialId?: string;
  quantity?: number;
  unitPrice?: number;
  lineDiscountPercent?: number;
  lineDiscountAmount?: number;
  bonus?: number;
  shelfId?: string;
  realEstateFloorLabel?: string;
  realEstatePartLabel?: string;
} | null | undefined): 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 bonus = Number(item.bonus || 0);

  return !String(item.materialId || '').trim()
    && quantity === 1
    && unitPrice === 0
    && lineDiscountPercent === 0
    && lineDiscountAmount === 0
    && bonus === 0
    && !String(item.shelfId || '').trim()
    && !String(item.realEstateFloorLabel || '').trim()
    && !String(item.realEstatePartLabel || '').trim();
}

const purchaseOrderSchema = z.object({
  supplierId: z.string().min(1, 'Please select a supplier.'),
  supplierInvoiceNumber: z.string().optional().default(''),
  supplierInvoiceDate: z.string().optional().default(''),
  currencyCode: z.string().min(1, 'Please choose a currency.'),
  baseCurrencyCode: z.string().optional(),
  exchangeRate: z.coerce.number().min(0.0001, 'Exchange rate is required.'),
  rateDate: z.string().min(1, 'Rate date is required.'),
  rateSource: z.string().optional(),
  isAutoRate: z.coerce.boolean().optional().default(true),
  warehouseId: z.string().optional(),
  realEstateLinkMode: z.enum(['none', 'order', 'line-items']).optional().default('none'),
  realEstateProjectId: z.string().optional().default(''),
  realEstateProjectName: z.string().optional().default(''),
  realEstateScope: z.enum(['project', 'floor', 'part']).optional().default('project'),
  realEstateFloorLabel: z.string().optional().default(''),
  realEstatePartLabel: z.string().optional().default(''),
  realEstateAllocationMethod: z.enum(['area', 'sale-value', 'manual-share']).optional().default('area'),
  allowDuplicateInvoice: z.coerce.boolean().optional().default(false),
  amountPaid: z.coerce.number().min(0, 'Amount paid must be a positive number.').default(0),
  paymentMethods: z.array(z.object({
    method: z.enum(['cash', 'check', 'bank_transfer', 'credit']),
    amount: z.coerce.number().min(0),
    currency: z.string().optional(),
    checkSource: z.enum(['issued', 'incoming']).optional(),
    incomingCheckIds: z.array(z.string()).optional(),
    checkNumber: z.string().optional(),
    checkDate: z.string().optional(),
    bankId: z.string().optional(),
    bankName: z.string().optional(),
    reference: z.string().optional(),
  })).optional().default([]),
  taxMethod: z.enum(['tax-inclusive', 'invoice-level', 'line-level', 'tax-exempt']).optional().default('tax-inclusive'),
  invoiceTaxRate: z.coerce.number().min(0).max(100).optional().default(0),
  invoiceDiscountPercent: z.coerce.number().min(0).max(100).optional().default(0),
  invoiceDiscountAmount: z.coerce.number().min(0).optional().default(0),
  notes: z.string().optional().default(''),
  items: z.array(z.object({
    materialId: z.string().optional().default(''),
    quantity: z.coerce.number().min(1, 'Quantity must be at least 1.'),
    unitPrice: z.coerce.number().min(0, 'Price must be a positive number.'),
    lineDiscountPercent: z.coerce.number().min(0).max(100).optional().default(0),
    lineDiscountAmount: z.coerce.number().min(0).optional().default(0),
    bonus: z.coerce.number().min(0).optional().default(0),
    warehouseId: z.string().optional().default(''),
    shelfId: z.string().optional().default(''),
    taxRate: z.coerce.number().min(0).max(100).optional(),
    realEstateProjectId: z.string().optional().default(''),
    realEstateProjectName: z.string().optional().default(''),
    realEstateScope: z.enum(['project', 'floor', 'part']).optional(),
    realEstateFloorLabel: z.string().optional().default(''),
    realEstatePartLabel: z.string().optional().default(''),
    realEstateAllocationMethod: z.enum(['area', 'sale-value', 'manual-share']).optional().default('area'),
  }).superRefine((item, ctx) => {
    if (isEffectivelyEmptyPurchaseItem(item)) {
      return;
    }

    if (!String(item.materialId || '').trim()) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['materialId'],
        message: 'Please select an item.',
      });
    }
  })).min(1, 'Please add at least one item to the order.'),
  documents: z.array(z.object({
    id: z.string().min(1),
    name: z.string().min(1),
    filePath: z.string().min(1),
    mimeType: z.string().optional(),
    size: z.coerce.number().min(0).optional(),
    uploadedAt: z.string().min(1),
    uploadedBy: z.string().optional(),
  })).optional().default([]),
  documentType: z.enum(['shipment', 'tax_invoice']).optional().default('tax_invoice'),
  linkedShipmentIds: z.array(z.string()).optional().default([]),
}).superRefine((data, ctx) => {
  const activeItems = (data.items || []).filter((item) => !isEffectivelyEmptyPurchaseItem(item));
  if (activeItems.length === 0) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['items'],
      message: 'Please add at least one item to the order.',
    });
  }
});

type Party = {
  id: string;
  name: string;
  type: 'customer' | 'supplier';
  originalId: string;
};

type PaymentTabMode = 'cash' | 'check' | 'bank_transfer' | 'credit' | 'mixed';

type IssuedCheckRow = {
  id: string;
  checkNumber: string;
  bankId: string;
  bankName: string;
  checkDate: string;
  amount: number;
  currency: string;
};

type PurchasePriceReviewRow = {
  materialId: string;
  materialName: string;
  previousPrice: number;         // converted to current invoice currency
  previousOriginalPrice: number; // original price in source currency
  previousCurrencyCode: string;  // source currency of the historical price
  newPrice: number;
  difference: number;
  changeType: 'increase' | 'decrease';
};

type PendingPriceReviewSubmission = {
  data: z.infer<typeof purchaseOrderSchema>;
  allowDuplicateOverride: boolean;
  postingType: 'draft' | 'saved' | 'posted';
  purchaseTransferCreationMode: PurchaseTransferCreationMode;
};

type PurchaseTransferCreationMode = 'direct_internal_transfer' | 'work_task' | 'none';

type PurchaseOrderFormProps = {
  suppliers: Supplier[];
  customers: Customer[];
  materials: ProductionItem[];
  purchaseOrders?: PurchaseOrder[];
  itemGroups?: ItemGroup[];
  categories?: CustomerCategory[];
  t: any;
  tGlobal: any;
  currencySymbol?: string;
  currencies?: Currency[];
  baseCurrency?: Currency;
  exchangeRateSources?: string[];
  stockLocationsByMaterial?: Record<string, MaterialStockReport['locations']>;
  materialShelfHistoryByMaterial?: Record<string, string[]>;
  warehouses?: Warehouse[];
  incomingChecks?: IncomingCheck[];
  banks?: Bank[];
  chartOfAccounts?: ChartOfAccount[];
  realEstateProjects?: RealEstateProject[];
  realEstateEnabled?: boolean;
  warehouseConfig?: {
    enabled: boolean;
    defaultWarehouseId?: string;
    defaultShelfId?: string;
  };
  defaultTaxMethod?: 'tax-inclusive' | 'invoice-level' | 'line-level' | 'tax-exempt';
  defaultTaxRate?: number;
  mode?: 'create' | 'edit';
  existingOrder?: PurchaseOrder | null;
  actionGuardToken: string;
  shipmentWorkflowEnabled?: boolean;
  aiInvoiceEntryEnabled?: boolean;
  purchasePostingFollowupEnabled?: boolean;
};

type IncomingChecksSortKey = 'checkNumber' | 'customerName' | 'checkDate' | 'bankName' | 'amount' | 'currency';

type IncomingChecksGridSelectorProps = {
  checks: IncomingCheck[];
  selectedIds: string[];
  onSelectionChange: (nextIds: string[]) => void;
  toCurrencyCode: string;
  convertedDisplayCurrency: string;
  defaultBaseCurrencyCode: string;
  convertAmountByRates: (amount: number, fromCurrency: string, toCurrency: string) => number;
  t: any;
};

function IncomingChecksGridSelector({
  checks,
  selectedIds,
  onSelectionChange,
  toCurrencyCode,
  convertedDisplayCurrency,
  defaultBaseCurrencyCode,
  convertAmountByRates,
  t,
}: IncomingChecksGridSelectorProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [sortKey, setSortKey] = useState<IncomingChecksSortKey>('checkDate');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [columnFilters, setColumnFilters] = useState({
    checkNumber: '',
    customerName: '',
    checkDate: '',
    bankName: '',
    amount: '',
    currency: '',
  });

  const visibleChecks = useMemo(() => {
    const normalizedSearch = searchQuery.trim().toLowerCase();
    const normalizedFilters = {
      checkNumber: columnFilters.checkNumber.trim().toLowerCase(),
      customerName: columnFilters.customerName.trim().toLowerCase(),
      checkDate: columnFilters.checkDate.trim().toLowerCase(),
      bankName: columnFilters.bankName.trim().toLowerCase(),
      amount: columnFilters.amount.trim().toLowerCase(),
      currency: columnFilters.currency.trim().toLowerCase(),
    };

    const filtered = checks.filter((entry) => {
      const amountText = String(Number(entry.amount || 0));
      const normalizedDate = entry.checkDate ? formatDateStable(entry.checkDate).toLowerCase() : '';

      if (normalizedSearch) {
        const searchTarget = [
          entry.checkNumber,
          entry.customerName,
          entry.bankName,
          normalizedDate,
          entry.currency,
          amountText,
        ].join(' ').toLowerCase();
        if (!searchTarget.includes(normalizedSearch)) return false;
      }

      if (normalizedFilters.checkNumber && !String(entry.checkNumber || '').toLowerCase().includes(normalizedFilters.checkNumber)) return false;
      if (normalizedFilters.customerName && !String(entry.customerName || '').toLowerCase().includes(normalizedFilters.customerName)) return false;
      if (normalizedFilters.checkDate && !normalizedDate.includes(normalizedFilters.checkDate)) return false;
      if (normalizedFilters.bankName && !String(entry.bankName || '').toLowerCase().includes(normalizedFilters.bankName)) return false;
      if (normalizedFilters.amount && !amountText.toLowerCase().includes(normalizedFilters.amount)) return false;
      if (normalizedFilters.currency && !String(entry.currency || '').toLowerCase().includes(normalizedFilters.currency)) return false;

      return true;
    });

    const sorted = [...filtered].sort((a, b) => {
      if (sortKey === 'amount') {
        return Number(a.amount || 0) - Number(b.amount || 0);
      }

      if (sortKey === 'checkDate') {
        return String(a.checkDate || '').localeCompare(String(b.checkDate || ''), 'ar');
      }

      const aValue = String(a[sortKey] || '');
      const bValue = String(b[sortKey] || '');
      return aValue.localeCompare(bValue, 'ar');
    });

    return sortDir === 'asc' ? sorted : sorted.reverse();
  }, [checks, searchQuery, columnFilters, sortKey, sortDir]);

  const selectedIdSet = useMemo(() => new Set(selectedIds), [selectedIds]);
  const visibleIds = useMemo(() => visibleChecks.map((entry) => entry.id), [visibleChecks]);
  const selectedVisibleCount = useMemo(
    () => visibleIds.reduce((count, id) => count + (selectedIdSet.has(id) ? 1 : 0), 0),
    [visibleIds, selectedIdSet]
  );
  const areAllVisibleSelected = visibleIds.length > 0 && selectedVisibleCount === visibleIds.length;

  const toggleSort = (nextKey: IncomingChecksSortKey) => {
    setSortKey((prevKey) => {
      if (prevKey === nextKey) {
        setSortDir((prevDir) => (prevDir === 'asc' ? 'desc' : 'asc'));
        return prevKey;
      }
      setSortDir('asc');
      return nextKey;
    });
  };

  const renderSortMark = (key: IncomingChecksSortKey) => {
    if (sortKey !== key) return <ChevronsUpDown className="h-3.5 w-3.5 text-black/50" />;
    return sortDir === 'asc' ? <ChevronUp className="h-3.5 w-3.5 text-black/80" /> : <ChevronDown className="h-3.5 w-3.5 text-black/80" />;
  };

  const updateColumnFilter = (key: keyof typeof columnFilters, value: string) => {
    setColumnFilters((prev) => ({ ...prev, [key]: value }));
  };

  return (
    <div className="space-y-2">
      <Input
        value={searchQuery}
        onChange={(event) => setSearchQuery(event.currentTarget.value)}
        placeholder={t?.search ?? 'بحث في الشيكات (رقم الشيك، العميل، البنك...)'}
        className="h-9 text-sm text-black/90 placeholder:text-black/50"
      />

      <div className="max-h-64 overflow-auto rounded-md border">
        <Table className="text-sm">
          <TableHeader className="sticky top-0 z-10 bg-background">
            <TableRow className="bg-background hover:bg-background">
              <TableHead className="w-10">
                <Checkbox
                  checked={areAllVisibleSelected ? true : (selectedVisibleCount > 0 ? 'indeterminate' : false)}
                  onCheckedChange={(checked) => {
                    const checkedValue = checked === true;
                    if (checkedValue) {
                      const nextIds = Array.from(new Set([...selectedIds, ...visibleIds]));
                      onSelectionChange(nextIds);
                      return;
                    }
                    const visibleSet = new Set(visibleIds);
                    onSelectionChange(selectedIds.filter((id) => !visibleSet.has(id)));
                  }}
                  aria-label={t?.selectAll ?? 'تحديد الكل'}
                />
              </TableHead>
              <TableHead>
                <Button type="button" variant="ghost" className="h-7 gap-1 px-1 text-black/90" onClick={() => toggleSort('checkNumber')}>
                  {t?.paymentCheckNumber ?? 'رقم الشيك'}
                  {renderSortMark('checkNumber')}
                </Button>
              </TableHead>
              <TableHead>
                <Button type="button" variant="ghost" className="h-7 gap-1 px-1 text-black/90" onClick={() => toggleSort('customerName')}>
                  {t?.customer ?? 'العميل'}
                  {renderSortMark('customerName')}
                </Button>
              </TableHead>
              <TableHead>
                <Button type="button" variant="ghost" className="h-7 gap-1 px-1 text-black/90" onClick={() => toggleSort('checkDate')}>
                  {t?.paymentCheckDate ?? 'تاريخ الشيك'}
                  {renderSortMark('checkDate')}
                </Button>
              </TableHead>
              <TableHead>
                <Button type="button" variant="ghost" className="h-7 gap-1 px-1 text-black/90" onClick={() => toggleSort('bankName')}>
                  {t?.paymentBankName ?? 'اسم البنك'}
                  {renderSortMark('bankName')}
                </Button>
              </TableHead>
              <TableHead>
                <Button type="button" variant="ghost" className="h-7 gap-1 px-1 text-black/90" onClick={() => toggleSort('amount')}>
                  {t?.amount ?? 'المبلغ'}
                  {renderSortMark('amount')}
                </Button>
              </TableHead>
              <TableHead>
                <Button type="button" variant="ghost" className="h-7 gap-1 px-1 text-black/90" onClick={() => toggleSort('currency')}>
                  {t?.currency ?? 'العملة'}
                  {renderSortMark('currency')}
                </Button>
              </TableHead>
              <TableHead className="text-black/90">{t?.convertedAmount ?? 'بعد التحويل'}</TableHead>
            </TableRow>
            <TableRow className="bg-background/95 hover:bg-background/95">
              <TableHead className="w-10" />
              <TableHead>
                <Input
                  value={columnFilters.checkNumber}
                  onChange={(event) => updateColumnFilter('checkNumber', event.currentTarget.value)}
                  placeholder={t?.filter ?? 'فلتر'}
                  className="h-7 text-xs text-black/90"
                />
              </TableHead>
              <TableHead>
                <Input
                  value={columnFilters.customerName}
                  onChange={(event) => updateColumnFilter('customerName', event.currentTarget.value)}
                  placeholder={t?.filter ?? 'فلتر'}
                  className="h-7 text-xs text-black/90"
                />
              </TableHead>
              <TableHead>
                <Input
                  value={columnFilters.checkDate}
                  onChange={(event) => updateColumnFilter('checkDate', event.currentTarget.value)}
                  placeholder={t?.filter ?? 'فلتر'}
                  className="h-7 text-xs text-black/90"
                />
              </TableHead>
              <TableHead>
                <Input
                  value={columnFilters.bankName}
                  onChange={(event) => updateColumnFilter('bankName', event.currentTarget.value)}
                  placeholder={t?.filter ?? 'فلتر'}
                  className="h-7 text-xs text-black/90"
                />
              </TableHead>
              <TableHead>
                <Input
                  value={columnFilters.amount}
                  onChange={(event) => updateColumnFilter('amount', event.currentTarget.value)}
                  placeholder={t?.filter ?? 'فلتر'}
                  className="h-7 text-xs text-black/90"
                />
              </TableHead>
              <TableHead>
                <Input
                  value={columnFilters.currency}
                  onChange={(event) => updateColumnFilter('currency', event.currentTarget.value)}
                  placeholder={t?.filter ?? 'فلتر'}
                  className="h-7 text-xs text-black/90"
                />
              </TableHead>
              <TableHead />
            </TableRow>
          </TableHeader>
          <TableBody>
            {visibleChecks.length === 0 ? (
              <TableRow>
                <TableCell colSpan={8} className="py-4 text-center text-sm text-black/70">
                  {t?.noIncomingChecksAvailable ?? 'لا توجد شيكات واردة مطابقة لشرط البحث/الفلترة.'}
                </TableCell>
              </TableRow>
            ) : (
              visibleChecks.map((entry) => {
                const rowSelected = selectedIdSet.has(entry.id);
                const convertedAmount = convertAmountByRates(
                  Number(entry.amount || 0),
                  entry.currency || defaultBaseCurrencyCode,
                  toCurrencyCode || defaultBaseCurrencyCode
                );

                return (
                  <TableRow key={entry.id} data-state={rowSelected ? 'selected' : undefined}>
                    <TableCell>
                      <Checkbox
                        checked={rowSelected}
                        onCheckedChange={(checked) => {
                          const checkedValue = checked === true;
                          if (checkedValue) {
                            onSelectionChange(Array.from(new Set([...selectedIds, entry.id])));
                            return;
                          }
                          onSelectionChange(selectedIds.filter((id) => id !== entry.id));
                        }}
                        aria-label={`${t?.select ?? 'تحديد'} ${entry.checkNumber}`}
                      />
                    </TableCell>
                    <TableCell className="font-semibold text-black/90">{entry.checkNumber}</TableCell>
                    <TableCell className="text-black/90">{entry.customerName}</TableCell>
                    <TableCell className="text-black/80">{entry.checkDate ? formatDateStable(entry.checkDate) : '-'}</TableCell>
                    <TableCell className="text-black/80">{entry.bankName || '-'}</TableCell>
                    <TableCell className="text-black/90">{formatCurrency(Number(entry.amount || 0), entry.currency || defaultBaseCurrencyCode)}</TableCell>
                    <TableCell className="text-black/80">{entry.currency || defaultBaseCurrencyCode}</TableCell>
                    <TableCell className="text-black/80">{formatCurrency(convertedAmount, convertedDisplayCurrency)}</TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>

      <p className="text-xs text-black/70">
        {t?.selected ?? 'المحدد'}: {selectedIds.length} | {t?.visible ?? 'المعروض'}: {visibleChecks.length}
      </p>
    </div>
  );
}

export default function PurchaseOrderForm({ suppliers, customers, materials, purchaseOrders = [], itemGroups = [], categories = [], t, tGlobal, currencySymbol = '$', currencies = [], baseCurrency, exchangeRateSources = [], stockLocationsByMaterial = {}, materialShelfHistoryByMaterial = {}, warehouses = [], incomingChecks = [], banks = [], chartOfAccounts = [], realEstateProjects = [], realEstateEnabled = false, warehouseConfig, defaultTaxMethod = 'tax-inclusive', defaultTaxRate = 0, mode = 'create', existingOrder = null, actionGuardToken, shipmentWorkflowEnabled = false, aiInvoiceEntryEnabled = false, purchasePostingFollowupEnabled = false }: PurchaseOrderFormProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
    const tablePreferencesStorageKey = 'purchase-order-grid-preferences';
    const defaultColumnWidths = {
      item: 240,
      quantity: 88,
      price: 110,
      shelf: 110,
      discountPercent: 88,
      discountAmount: 96,
      bonus: 88,
      total: 110,
    };
    const minColumnWidths = {
      item: 170,
      quantity: 72,
      price: 88,
      shelf: 92,
      discountPercent: 76,
      discountAmount: 84,
      bonus: 76,
      total: 96,
    };
    // Grid State: إدارة بيانات items محليًا
    const [gridItems, setGridItems] = useState<z.infer<typeof purchaseOrderSchema>["items"]>([]);
    const [activeGridRowIndex, setActiveGridRowIndex] = useState<number | null>(null);
    const [paymentMethods, setPaymentMethods] = useState<z.infer<typeof purchaseOrderSchema>["paymentMethods"]>([]);
    const [paymentTabMode, setPaymentTabMode] = useState<PaymentTabMode>('credit');
    const [issuedChecks, setIssuedChecks] = useState<IssuedCheckRow[]>([]);
    const [issuedCheckDraft, setIssuedCheckDraft] = useState<IssuedCheckRow>({
      id: 'draft',
      checkNumber: '',
      bankId: '',
      bankName: '',
      checkDate: format(new Date(), 'yyyy-MM-dd'),
      amount: 0,
      currency: 'USD',
    });
    const [showItemDescriptions, setShowItemDescriptions] = useState(false);
    const [showOrderHeaderDetails, setShowOrderHeaderDetails] = useState(true);
    const appendGridItem = (item: z.infer<typeof purchaseOrderSchema>["items"][number]) => setGridItems(prev => [...prev, item]);
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [selectedPartyId, setSelectedPartyId] = useState<string>('');
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [barcodeInput, setBarcodeInput] = useState("");
  const [orderDocuments, setOrderDocuments] = useState<PurchaseOrderDocument[]>(existingOrder?.documents || []);
  const [isUploadingDocument, setIsUploadingDocument] = useState(false);
  const [orderDateLabel, setOrderDateLabel] = useState('');
  const [showAddSupplierDialog, setShowAddSupplierDialog] = useState(false);
  const [showAddMaterialDialog, setShowAddMaterialDialog] = useState(false);
  const [addMaterialInitialValues, setAddMaterialInitialValues] = useState<Partial<ProductionItem> | undefined>(undefined);
  const [extraMaterials, setExtraMaterials] = useState<ProductionItem[]>([]);
  const [showWeightDialog, setShowWeightDialog] = useState(false);
  const [weightInput, setWeightInput] = useState("");
  const [pendingWeightMaterial, setPendingWeightMaterial] = useState<ProductionItem | null>(null);
  const [pendingWeightUnitPrice, setPendingWeightUnitPrice] = useState(0);
  const [pendingWeightDescription, setPendingWeightDescription] = useState('');
  const [pendingMeasurementMode, setPendingMeasurementMode] = useState<'weight' | 'volume'>('weight');
  const [pendingVolumeOptions, setPendingVolumeOptions] = useState<Array<{ key: string; label: string; price: number; barcode?: string }>>([]);
  const [selectedVolumeOptionKey, setSelectedVolumeOptionKey] = useState('');
  const [stockReport, setStockReport] = useState<MaterialStockReport[] | null>(null);
  const [showStockReportDialog, setShowStockReportDialog] = useState(false);
  const [columnVisibility, setColumnVisibility] = useState({
    shelf: true,
    discountPercent: true,
    discountAmount: true,
    bonus: true,
    total: true,
  });
  const [columnWidths, setColumnWidths] = useState(defaultColumnWidths);
  const [draggingRowIndex, setDraggingRowIndex] = useState<number | null>(null);
  const [resizingColumnKey, setResizingColumnKey] = useState<keyof typeof defaultColumnWidths | null>(null);
  const [mounted, setMounted] = useState(false);
  const [isAcquiringEditLock, setIsAcquiringEditLock] = useState(mode === 'edit');
  const [hasEditLock, setHasEditLock] = useState(mode !== 'edit');
  const editLockOwnedRef = useRef(false);
  const editLockOrderIdRef = useRef<string | null>(null);
  const initializedOrderIdRef = useRef<string | null>(null);
  const resizeStateRef = useRef<{
    key: keyof typeof defaultColumnWidths;
    startX: number;
    startWidth: number;
  } | null>(null);
  const submitButtonRef = useRef<HTMLButtonElement | null>(null);
  const submitCooldownRef = useRef(0);
  const submitOriginRef = useRef('unknown');
  const submitAttemptCooldownRef = useRef(0);
  const documentInputRef = useRef<HTMLInputElement | null>(null);
  const blurActiveElement = () => {
    const active = document.activeElement as HTMLElement | null;
    if (active && typeof active.blur === 'function') {
      active.blur();
    }
  };
  const [supplierList, setSupplierList] = useState(suppliers);
  const [customerList, setCustomerList] = useState(customers);
  const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
  const [duplicateInfo, setDuplicateInfo] = useState<PurchaseOrder | null>(null);
  const [pendingSubmit, setPendingSubmit] = useState<z.infer<typeof purchaseOrderSchema> | null>(null);
  const [pendingPostingSubmit, setPendingPostingSubmit] = useState<z.infer<typeof purchaseOrderSchema> | null>(null);
  const [postingDialogOpen, setPostingDialogOpen] = useState(false);
  const [postingType, setPostingType] = useState<'draft' | 'saved' | 'posted'>('saved');
  const [pendingPostingType, setPendingPostingType] = useState<'draft' | 'saved' | 'posted'>('saved');
  const [postingFollowupDialogOpen, setPostingFollowupDialogOpen] = useState(false);
  const [purchaseTransferCreationMode, setPurchaseTransferCreationMode] = useState<PurchaseTransferCreationMode>('work_task');
  const [pendingTransferCreationMode, setPendingTransferCreationMode] = useState<PurchaseTransferCreationMode>('work_task');
  const [priceReviewDialogOpen, setPriceReviewDialogOpen] = useState(false);
  const [priceReviewRows, setPriceReviewRows] = useState<PurchasePriceReviewRow[]>([]);
  const [pendingPriceReviewSubmission, setPendingPriceReviewSubmission] = useState<PendingPriceReviewSubmission | null>(null);
  const [itemSelectQuery, setItemSelectQuery] = useState('');
  const [showItemPicker, setShowItemPicker] = useState(false);
  const [itemPickerQuery, setItemPickerQuery] = useState('');
  const [itemPickerInputResetKey, setItemPickerInputResetKey] = useState(0);
  const itemPickerInputRef = useRef<HTMLInputElement | null>(null);
  const itemPickerScrollRef = useRef<HTMLDivElement | null>(null);
  const [itemPickerScrollTop, setItemPickerScrollTop] = useState(0);
  const [pickerTargetRowIndex, setPickerTargetRowIndex] = useState<number | null>(null);
  const [autoUpdateSalePrice, setAutoUpdateSalePrice] = useState(false);
  const [updateMaterialDialogOpen, setUpdateMaterialDialogOpen] = useState(false);
  const [updateMaterialItem, setUpdateMaterialItem] = useState<ProductionItem | null>(null);
  const [showPurchasePriceDialog, setShowPurchasePriceDialog] = useState(false);
  const [purchasePriceDialogMaterialId, setPurchasePriceDialogMaterialId] = useState<string | null>(null);
  const [itemContextMenu, setItemContextMenu] = useState<{ x: number; y: number; materialId: string } | null>(null);
  const [supplierInvoiceDuplicateInfo, setSupplierInvoiceDuplicateInfo] = useState<PurchaseOrder | null>(null);
  const [isRtlLayout, setIsRtlLayout] = useState(false);
  const isDuplicatedDraft = mode === 'edit' && searchParams?.get('duplicated') === '1';

  // Shipment Workflow state
  const [documentType, setDocumentType] = useState<'shipment' | 'tax_invoice'>(
    existingOrder?.documentType || 'tax_invoice'
  );
  const [availableShipments, setAvailableShipments] = useState<PurchaseOrder[]>([]);
  const [linkedShipmentIds, setLinkedShipmentIds] = useState<string[]>(existingOrder?.linkedShipmentIds || []);
  const [shipmentPanelOpen, setShipmentPanelOpen] = useState(false);
  const [isLoadingShipments, setIsLoadingShipments] = useState(false);
  const isWarehouseEnabled = warehouseConfig?.enabled === true;
  const isRealEstateEnabled = realEstateEnabled === true;

  // AI Invoice Entry state
  const [aiExtractionDialogOpen, setAiExtractionDialogOpen] = useState(false);
  const [aiExtractionMode, setAiExtractionMode] = useState<'image' | 'voice'>('image');
  const [isAiExtracting, setIsAiExtracting] = useState(false);
  const [aiExtractionDocument, setAiExtractionDocument] = useState<PurchaseOrderDocument | null>(null);
  const [aiExtractionVoiceText, setAiExtractionVoiceText] = useState('');
  const [aiExtractionResult, setAiExtractionResult] = useState<any>(null);
  const [aiExtractionConfidence, setAiExtractionConfidence] = useState(0);
  const [aiReviewDialogOpen, setAiReviewDialogOpen] = useState(false);
  const defaultWarehouseId = isWarehouseEnabled ? warehouseConfig?.defaultWarehouseId || '' : '';
  const defaultShelfId = isWarehouseEnabled ? warehouseConfig?.defaultShelfId || '' : '';
  const defaultBaseCurrencyCode = useMemo(() => baseCurrency?.code || currencies.find((c) => c.isDefault)?.code || 'USD', [baseCurrency, currencies]);
  const configuredRateSource = useMemo(
    () => String(baseCurrency?.source || exchangeRateSources[0] || 'https://www.xe.com').trim(),
    [baseCurrency, exchangeRateSources]
  );
  const defaultRateDate = useMemo(() => format(new Date(), 'yyyy-MM-dd'), []);

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

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

  const normalizeDecimalInput = (value: string) => {
    const english = toEnglishDigits(value);
    const sanitized = english.replace(/[^0-9.]/g, '');
    const dotIndex = sanitized.indexOf('.');
    if (dotIndex === -1) return sanitized;
    return `${sanitized.slice(0, dotIndex + 1)}${sanitized.slice(dotIndex + 1).replace(/\./g, '')}`;
  };

  const formatDecimalForInput = (value: number | string, maxDecimals = 3) => {
    const numeric = Number(value);
    if (!Number.isFinite(numeric)) return '';
    const rounded = numeric.toFixed(maxDecimals);
    return rounded.replace(/\.0+$/, '').replace(/(\.\d*?)0+$/, '$1');
  };

  useEffect(() => {
    setIssuedCheckDraft((prev) => ({
      ...prev,
      currency: prev.currency && prev.currency !== 'USD' ? prev.currency : (defaultBaseCurrencyCode || 'USD'),
      checkDate: prev.checkDate || defaultRateDate,
    }));
  }, [defaultBaseCurrencyCode, defaultRateDate]);
  const shelvesByWarehouse = useMemo(() => {
    const map = new Map<string, { id: string; name: string }[]>();
    warehouses.forEach((warehouse) => {
      map.set(warehouse.id, Array.isArray(warehouse.shelves) ? warehouse.shelves : []);
    });
    return map;
  }, [warehouses]);

  const paymentAccountOptions = useMemo(() => {
    const headersById = new Map(chartOfAccounts.map((acc) => [acc.id, acc]));
    return chartOfAccounts
      .filter((acc) => acc.type === 'account' && !acc.inactive)
      .map((acc) => {
        const parent = acc.parentId ? headersById.get(acc.parentId) : undefined;
        const parentName = parent ? (parent.nameAr || parent.nameEn || '') : '';
        const accountName = acc.nameAr || acc.nameEn || acc.code;
        const label = parentName ? `${acc.code} - ${accountName} (${parentName})` : `${acc.code} - ${accountName}`;
        return { id: acc.id, code: acc.code, label, name: accountName };
      });
  }, [chartOfAccounts]);

  const defaultCashAccount = useMemo(() => {
    return paymentAccountOptions.find((acc) => acc.code === '1110')
      || paymentAccountOptions.find((acc) => acc.code.startsWith('111'))
      || paymentAccountOptions[0]
      || null;
  }, [paymentAccountOptions]);

  const defaultBankAccount = useMemo(() => {
    return paymentAccountOptions.find((acc) => acc.code === '1120')
      || paymentAccountOptions.find((acc) => acc.code.startsWith('112'))
      || defaultCashAccount
      || null;
  }, [paymentAccountOptions, defaultCashAccount]);

  const getPrioritizedShelves = (materialId: string, warehouseId: string) => {
    const availableShelves = shelvesByWarehouse.get(warehouseId) ?? [];
    if (!materialId || !warehouseId || availableShelves.length === 0) return availableShelves;

    const currentShelfIds = new Set(
      (stockLocationsByMaterial[materialId] || [])
        .filter((entry) => entry.warehouseId === warehouseId && Number(entry.quantity || 0) > 0)
        .map((entry) => entry.shelfId)
    );

    const historicalShelfIds = new Set(
      (materialShelfHistoryByMaterial[materialId] || [])
        .filter((key) => key.startsWith(`${warehouseId}||`))
        .map((key) => key.split('||')[1])
        .filter(Boolean)
    );

    const getPriority = (shelfId: string) => {
      if (currentShelfIds.has(shelfId)) return 0;
      if (historicalShelfIds.has(shelfId)) return 1;
      return 2;
    };

    return [...availableShelves].sort((left, right) => {
      const prioDiff = getPriority(left.id) - getPriority(right.id);
      if (prioDiff !== 0) return prioDiff;
      return String(left.name || '').localeCompare(String(right.name || ''), 'ar');
    });
  };

  const isShelfColumnVisible = isWarehouseEnabled && columnVisibility.shelf;
  const editableColumns = useMemo(() => {
    let cursor = 0;
    const map: {
      item: number;
      quantity: number;
      price: number;
      shelf?: number;
      discountPercent?: number;
      discountAmount?: number;
      bonus?: number;
      total?: number;
      count: number;
    } = {
      item: cursor++,
      quantity: cursor++,
      price: cursor++,
      count: 0,
    };

    if (isShelfColumnVisible) map.shelf = cursor++;
    if (columnVisibility.discountPercent) map.discountPercent = cursor++;
    if (columnVisibility.discountAmount) map.discountAmount = cursor++;
    if (columnVisibility.bonus) map.bonus = cursor++;
    if (columnVisibility.total) map.total = cursor++;

    map.count = cursor;
    return map;
  }, [isShelfColumnVisible, columnVisibility.discountPercent, columnVisibility.discountAmount, columnVisibility.bonus, columnVisibility.total]);

  const moveGridRow = (fromIndex: number, toIndex: number) => {
    setGridItems((prev) => {
      if (fromIndex < 0 || fromIndex >= prev.length) return prev;
      const boundedTarget = Math.max(0, Math.min(toIndex, prev.length - 1));
      if (boundedTarget === fromIndex) return prev;
      const next = [...prev];
      const [moved] = next.splice(fromIndex, 1);
      next.splice(boundedTarget, 0, moved);
      return next;
    });
    setActiveGridRowIndex(Math.max(0, Math.min(toIndex, gridItems.length - 1)));
  };

  const startColumnResize = (key: keyof typeof defaultColumnWidths) => (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';
  };

  const renderResizeHandle = (key: keyof typeof defaultColumnWidths) => (
    <div
      className={cn(
        'absolute inset-y-0 -right-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={cn(
          'h-full w-px bg-border/80 transition-all',
          resizingColumnKey === key ? 'w-[2px] bg-emerald-500' : 'group-hover:bg-emerald-300'
        )}
      />
    </div>
  );

  // تنقل لوحة المفاتيح داخل جدول الأصناف
  const getEditableColumnCount = () => editableColumns.count;
  const focusCell = (rowIndex: number, colIndex: number) => {
    const target = document.querySelector<HTMLElement>(`[data-cell="${rowIndex}-${colIndex}"]`);
    if (target) target.focus();
  };

  const selectAllOnFocus = (e: React.FocusEvent<HTMLInputElement>) => {
    // Ensure the value is always selected when entering a cell so typing replaces it directly.
    requestAnimationFrame(() => {
      e.target.select();
    });
  };

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

  const handleNumberInputFocusCapture = (e: React.FocusEvent<HTMLElement>) => {
    const target = e.target as HTMLElement | null;
    if (!target || target.tagName !== 'INPUT') return;
    const input = target as HTMLInputElement;
    if (input.type !== 'number') return;
    
    // Skip auto-select if input has data-no-auto-select attribute
    if (input.dataset.noAutoSelect === 'true') return;

    requestAnimationFrame(() => {
      input.select();
    });
  };

  const handleNumberInputMouseDownCapture = (e: React.MouseEvent<HTMLElement>) => {
    const target = e.target as HTMLElement | null;
    if (!target || target.tagName !== 'INPUT') return;
    const input = target as HTMLInputElement;
    if (input.type !== 'number') return;
    
    // Skip auto-select if input has data-no-auto-select attribute
    if (input.dataset.noAutoSelect === 'true') return;

    if (document.activeElement !== input) {
      e.preventDefault();
      input.focus();
      input.select();
    }
  };

  const 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 any, rowIndex, colIndex);
      return;
    }
  };
  const handleGridKeyDown = (event: 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, gridItems.length - 1));
      setTimeout(() => focusCell(boundedRow, Math.max(0, Math.min(colIndex, getEditableColumnCount() - 1))), 0);
      return;
    }

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

    // لا نمنع فتح select إذا كان Alt+ArrowDown مثلًا
    if (event.key === 'ArrowDown' && (event.altKey || event.metaKey)) return;

    event.preventDefault();

    const colCount = getEditableColumnCount();
    let nextRow = rowIndex;
    let nextCol = colIndex;

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

    // التفاف الصفوف/الأعمدة
    if (nextCol >= colCount) {
      nextCol = 0;
      nextRow += 1;
    } else if (nextCol < 0) {
      nextCol = colCount - 1;
      nextRow -= 1;
    }

    if (nextRow < 0) nextRow = 0;
    if (nextRow >= gridItems.length) {
      const canAppendRow = event.key === 'Enter' || event.key === 'Tab' || event.key === 'ArrowRight';
      if (canAppendRow && !(event.key === 'Tab' && event.shiftKey)) {
        appendEmptyRow();
        nextRow = gridItems.length;
        nextCol = 0;
      } else {
        // ابقَ في آخر صف مدخل متاح
        nextRow = gridItems.length - 1;
        if (nextRow < 0) nextRow = 0;
      }
    }

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

  const handleFormHotkeys = (event: React.KeyboardEvent<HTMLFormElement>) => {
    if (event.key === 'F2') {
      event.preventDefault();
      if (event.repeat) {
        return;
      }
      const now = Date.now();
      if (now - submitCooldownRef.current < 800) {
        return;
      }
      if (!isPending && hasEditLock) {
        submitOriginRef.current = 'hotkey-f2';
        submitCooldownRef.current = now;
        submitButtonRef.current?.click();
      }
      return;
    }

    if (event.key !== 'Enter' || event.defaultPrevented || event.nativeEvent.isComposing) return;

    const target = event.target as HTMLElement | null;
    if (!target) return;

    const tagName = target.tagName;
    if (tagName === 'TEXTAREA') return;
    if (target.closest('[role="dialog"]') && !target.closest('form')) return;

    const isNativeInput =
      target.matches('input:not([type="hidden"])') ||
      target.matches('select') ||
      target.matches('textarea');

    if (!isNativeInput) return;

    const focusableElements = Array.from(
      event.currentTarget.querySelectorAll<HTMLElement>('input, select, textarea, button, [tabindex]:not([tabindex="-1"])')
    ).filter((element) => {
      if (element.hasAttribute('disabled')) return false;
      if (element.getAttribute('aria-hidden') === 'true') return false;
      if (element.matches('input[type="hidden"]')) return false;
      if (element.matches('button[type="submit"]')) return false;
      if (element.getClientRects().length === 0) return false;
      return true;
    });

    const currentIndex = focusableElements.indexOf(target);
    if (currentIndex === -1) return;

    const nextElement = focusableElements[currentIndex + 1];
    if (!nextElement) {
      event.preventDefault();
      return;
    }

    event.preventDefault();
    nextElement.focus();

    if (nextElement instanceof HTMLInputElement) {
      requestAnimationFrame(() => nextElement.select());
    }
  };

  const form = useForm<z.infer<typeof purchaseOrderSchema>>({
    resolver: zodResolver(purchaseOrderSchema),
    defaultValues: {
      supplierId: '',
      supplierInvoiceNumber: '',
      supplierInvoiceDate: defaultRateDate,
      currencyCode: defaultBaseCurrencyCode,
      baseCurrencyCode: defaultBaseCurrencyCode,
      exchangeRate: 1,
      rateDate: defaultRateDate,
      rateSource: configuredRateSource,
      isAutoRate: true,
      warehouseId: isWarehouseEnabled ? defaultWarehouseId : '',
      realEstateLinkMode: 'none',
      realEstateProjectId: '',
      realEstateProjectName: '',
      realEstateScope: 'project',
      realEstateFloorLabel: '',
      realEstatePartLabel: '',
      realEstateAllocationMethod: 'area',
      allowDuplicateInvoice: false,
      amountPaid: 0,
      paymentMethods: [],
      taxMethod: 'tax-inclusive',
      invoiceTaxRate: defaultTaxRate,
      invoiceDiscountPercent: 0,
      invoiceDiscountAmount: 0,
      notes: '',
      items: [],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'items',
  });

  // حافظ على تزامن gridItems مع حالة النموذج لحساب الخصومات والإجمالي بشكل صحيح
  useEffect(() => {
    form.setValue('items', gridItems, { shouldDirty: true, shouldValidate: true });
  }, [gridItems, form]);

  // Keep payment methods synchronized with form state
  useEffect(() => {
    form.setValue('paymentMethods', paymentMethods, { shouldDirty: true, shouldValidate: true });
  }, [paymentMethods, 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);
    };
  }, []);
  
  const parties = useMemo<Party[]>(() => {
    const supplierParties: Party[] = supplierList.map(s => ({
      id: `supplier:${s.id}`,
      name: s.name,
      type: 'supplier' as const,
      originalId: s.id
    }));
    const customerParties: Party[] = customerList.map(c => ({
      id: `customer:${c.id}`,
      name: c.name,
      type: 'customer' as const,
      originalId: c.id
    }));
    const combined = [...supplierParties, ...customerParties];
    // Deduplicate by ID to prevent React key warnings
    const seen = new Set<string>();
    return combined.filter(p => {
      if (seen.has(p.id)) return false;
      seen.add(p.id);
      return true;
    });
  }, [supplierList, customerList]);

  const selectedParty = useMemo(() => parties.find(p => p.id === selectedPartyId), [parties, selectedPartyId]);

  const selectedPartyInfo = useMemo(() => {
    if (!selectedParty) return undefined;
    if (selectedParty.type === 'supplier') {
      return supplierList.find(s => s.id === selectedParty.originalId);
    } else {
      return customerList.find(c => c.id === selectedParty.originalId);
    }
  }, [selectedParty, supplierList, customerList]);

  const selectedSupplier = useMemo(() => {
    if (!selectedParty || selectedParty.type !== 'supplier') return undefined;
    return supplierList.find(s => s.id === selectedParty.originalId);
  }, [selectedParty, supplierList]);

  const findDuplicateInvoice = (supplierId: string, invoiceNumber: string) => {
    const normalized = invoiceNumber.trim().toLowerCase();
    if (!supplierId || !normalized) return null;
    return purchaseOrders.find(
      (order) =>
        order.supplierId === supplierId &&
        order.id !== (existingOrder?.id || '') &&
        String(order.supplierInvoiceNumber || '').trim().toLowerCase() === normalized
    ) || null;
  };

  const getOrderStatusLabel = (order: PurchaseOrder) => {
    if (order.status === 'cancelled') {
      return t?.statusCancelled ?? 'ملغي';
    }

    if (order.status === 'received') {
      return t?.statusReceived ?? 'مستلم';
    }

    if (order.postingStatus === 'posted') {
      return t?.postingPostedLabel ?? 'مرحل';
    }

    if (order.postingStatus === 'draft') {
      return t?.postingDraftLabel ?? 'مسودة';
    }

    if (order.postingStatus === 'saved') {
      return t?.postingSavedLabel ?? 'محفوظ';
    }

    return t?.statusActive ?? 'نشط';
  };

  useEffect(() => {
    if (selectedPartyInfo) {
      form.setValue('supplierId', selectedPartyInfo.id);
    }
  }, [selectedPartyInfo, form]);

  useEffect(() => {
    const dateSource = existingOrder?.date ? new Date(existingOrder.date) : new Date();
    setOrderDateLabel(format(dateSource, 'PPP'));
  }, [existingOrder]);

  useEffect(() => {
    try {
      const rawPreferences = window.localStorage.getItem(tablePreferencesStorageKey);
      if (rawPreferences) {
        const parsed = JSON.parse(rawPreferences) as {
          columnVisibility?: Partial<typeof columnVisibility>;
          columnWidths?: Partial<typeof columnWidths>;
        };

        if (parsed.columnVisibility) {
          setColumnVisibility((prev) => ({
            ...prev,
            ...parsed.columnVisibility,
          }));
        }

        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)),
            price: Math.max(minColumnWidths.price, Number(parsed.columnWidths.price ?? prev.price)),
            shelf: Math.max(minColumnWidths.shelf, Number(parsed.columnWidths.shelf ?? prev.shelf)),
            discountPercent: Math.max(minColumnWidths.discountPercent, Number(parsed.columnWidths.discountPercent ?? prev.discountPercent)),
            discountAmount: Math.max(minColumnWidths.discountAmount, Number(parsed.columnWidths.discountAmount ?? prev.discountAmount)),
            bonus: Math.max(minColumnWidths.bonus, Number(parsed.columnWidths.bonus ?? prev.bonus)),
            total: Math.max(minColumnWidths.total, Number(parsed.columnWidths.total ?? prev.total)),
          }));
        }
      }
    } catch {
      // Ignore invalid local preferences and fall back to defaults.
    }

    setMounted(true);
  }, []);

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

    window.localStorage.setItem(
      tablePreferencesStorageKey,
      JSON.stringify({
        columnVisibility,
        columnWidths,
      })
    );
  }, [mounted, tablePreferencesStorageKey, columnVisibility, columnWidths]);

  useEffect(() => {
    if (!existingOrder) return;
    if (initializedOrderIdRef.current === existingOrder.id) return;
    initializedOrderIdRef.current = existingOrder.id;

    // حدد المورد الحالي
    setSelectedPartyId(`supplier:${existingOrder.supplierId}`);

    const inferredOrderWarehouseId = existingOrder.warehouseId
      || existingOrder.items?.find((line) => String(line.warehouseId || '').trim())?.warehouseId
      || '';

    // قيم النموذج الأساسية
    form.reset({
      supplierId: existingOrder.supplierId,
      supplierInvoiceNumber: existingOrder.supplierInvoiceNumber || '',
      supplierInvoiceDate: existingOrder.supplierInvoiceDate || defaultRateDate,
      currencyCode: existingOrder.currencyCode || defaultBaseCurrencyCode,
      baseCurrencyCode: existingOrder.baseCurrencyCode || defaultBaseCurrencyCode,
      exchangeRate: existingOrder.exchangeRate || 1,
      rateDate: (existingOrder.rateDate ? format(new Date(existingOrder.rateDate), 'yyyy-MM-dd') : defaultRateDate),
      rateSource: existingOrder.rateSource || configuredRateSource,
      isAutoRate: existingOrder.isAutoRate !== undefined ? existingOrder.isAutoRate : true,
      warehouseId: inferredOrderWarehouseId || (isWarehouseEnabled ? defaultWarehouseId : ''),
      realEstateLinkMode: existingOrder.realEstateLinkMode || 'none',
      realEstateProjectId: existingOrder.realEstateProjectId || '',
      realEstateProjectName: existingOrder.realEstateProjectName || '',
      realEstateScope: existingOrder.realEstateScope || 'project',
      realEstateFloorLabel: existingOrder.realEstateFloorLabel || '',
      realEstatePartLabel: existingOrder.realEstatePartLabel || '',
      realEstateAllocationMethod: existingOrder.realEstateAllocationMethod || 'area',
      allowDuplicateInvoice: true,
      amountPaid: existingOrder.amountPaid || 0,
      paymentMethods: existingOrder.paymentMethods || [],
      taxMethod: (existingOrder.taxMethod as any) || 'tax-inclusive',
      invoiceTaxRate: existingOrder.taxMethod === 'invoice-level' ? (existingOrder.taxAmount && existingOrder.subTotal ? (existingOrder.taxAmount / Math.max(existingOrder.subTotal - (existingOrder.invoiceDiscountAmount || 0), 1)) * 100 : defaultTaxRate) : defaultTaxRate,
      invoiceDiscountPercent: existingOrder.invoiceDiscountPercent || 0,
      invoiceDiscountAmount: existingOrder.invoiceDiscountAmount || 0,
      notes: existingOrder.notes || '',
      items: [],
    });

    // الأصناف في الجدول
    const mappedItems = (existingOrder.items || []).map((item) => ({
      materialId: item.materialId,
      quantity: item.quantity,
      unitPrice: item.unitPrice,
      lineDiscountPercent: item.lineDiscountPercent || 0,
      lineDiscountAmount: item.lineDiscountAmount || 0,
      bonus: item.bonus || 0,
      warehouseId: item.warehouseId || inferredOrderWarehouseId || '',
      shelfId: item.shelfId || '',
      taxRate: item.taxRate || 0,
      realEstateProjectId: item.realEstateProjectId || existingOrder.realEstateProjectId || '',
      realEstateProjectName: item.realEstateProjectName || existingOrder.realEstateProjectName || '',
      realEstateScope: item.realEstateScope || undefined,
      realEstateFloorLabel: item.realEstateFloorLabel || '',
      realEstatePartLabel: item.realEstatePartLabel || '',
      realEstateAllocationMethod: item.realEstateAllocationMethod || (item.realEstateScope === 'project' ? existingOrder.realEstateAllocationMethod || 'area' : undefined),
    }));
    setOrderDocuments(existingOrder.documents || []);
    setGridItems(mappedItems);
    setPaymentMethods(existingOrder.paymentMethods || []);
    setIssuedChecks(
      (existingOrder.paymentMethods || [])
        .filter((m) => m.method === 'check' && m.checkSource === 'issued')
        .map((m, idx) => ({
          id: m.id || `existing-issued-${idx + 1}`,
          checkNumber: m.checkNumber || '',
          bankId: m.bankId || '',
          bankName: m.bankName || '',
          checkDate: m.checkDate || defaultRateDate,
          amount: Number(m.amount || 0),
          currency: (m as { currency?: string }).currency || m.currencyCode || defaultBaseCurrencyCode,
        }))
    );
    const existingMethods = existingOrder.paymentMethods || [];
    if (existingMethods.length > 1) {
      setPaymentTabMode('mixed');
    } else if (existingMethods.length === 1) {
      setPaymentTabMode((existingMethods[0].method as PaymentTabMode) || 'credit');
    } else {
      setPaymentTabMode('credit');
    }
    setPostingType((existingOrder.postingStatus as 'draft' | 'saved' | 'posted') || 'saved');
    setPurchaseTransferCreationMode(existingOrder.purchaseTransferCreationMode || 'work_task');
    setPendingTransferCreationMode(existingOrder.purchaseTransferCreationMode || 'work_task');
    setSupplierInvoiceDuplicateInfo(null);
  }, [existingOrder, isWarehouseEnabled, defaultWarehouseId, defaultTaxMethod, defaultTaxRate, defaultRateDate, defaultBaseCurrencyCode, configuredRateSource, form]);

  useEffect(() => {
    if (!configuredRateSource) return;
    if (!form.getValues('rateSource')) {
      form.setValue('rateSource', configuredRateSource, { shouldDirty: false });
    }
  }, [configuredRateSource, form]);

  useEffect(() => {
    if (!selectedPartyInfo) {
      setSupplierInvoiceDuplicateInfo(null);
      return;
    }

    const invoiceNumber = String(form.getValues('supplierInvoiceNumber') || '').trim();
    if (!invoiceNumber) {
      setSupplierInvoiceDuplicateInfo(null);
      return;
    }

    setSupplierInvoiceDuplicateInfo(findDuplicateInvoice(selectedPartyInfo.id, invoiceNumber));
  }, [selectedPartyInfo, form]);

  useEffect(() => {
    if (mode !== 'edit' || !existingOrder?.id) {
      setIsAcquiringEditLock(false);
      setHasEditLock(true);
      editLockOwnedRef.current = false;
      editLockOrderIdRef.current = null;
      return;
    }

    // If lock already acquired for this order, do not reacquire.
    if (editLockOwnedRef.current && editLockOrderIdRef.current === existingOrder.id) {
      setIsAcquiringEditLock(false);
      setHasEditLock(true);
      return;
    }

    let cancelled = false;
    setIsAcquiringEditLock(true);

    const acquire = async () => {
      const result = await handleAcquirePurchaseOrderLock(existingOrder.id);
      if (cancelled) return;

      if (result?.success) {
        editLockOwnedRef.current = true;
        editLockOrderIdRef.current = existingOrder.id;
        setHasEditLock(true);
      } else {
        editLockOwnedRef.current = false;
        editLockOrderIdRef.current = null;
        setHasEditLock(false);
        toast({
          title: tGlobal?.error || 'خطأ',
          description: (t?.purchaseOrderLockedBy || 'يتم التعديل على الفاتورة من قبل {name}.').replace('{name}', result?.lockedBy || 'مستخدم آخر'),
          variant: 'destructive',
        });
        router.push('/admin/purchases/history');
      }

      setIsAcquiringEditLock(false);
    };

    void acquire();

    return () => {
      cancelled = true;
    };
  }, [mode, existingOrder?.id]);

  useEffect(() => {
    return () => {
      if (editLockOwnedRef.current && editLockOrderIdRef.current) {
        void handleReleasePurchaseOrderLock(editLockOrderIdRef.current);
        editLockOwnedRef.current = false;
        editLockOrderIdRef.current = null;
      }
    };
  }, []);

  const allMaterials = useMemo(() => {
    const merged: ProductionItem[] = [];
    const seen = new Set<string>();
    for (const item of materials) {
      if (!item?.id || seen.has(item.id)) continue;
      merged.push(item);
      seen.add(item.id);
    }
    for (const item of extraMaterials) {
      if (!item?.id || seen.has(item.id)) continue;
      merged.push(item);
      seen.add(item.id);
    }
    return merged;
  }, [extraMaterials, materials]);

  const materialsById = useMemo(() => {
    return new Map(allMaterials.map((material) => [material.id, material]));
  }, [allMaterials]);

  const realEstateProjectsById = useMemo(() => {
    return new Map(realEstateProjects.map((project) => [String(project.id || '').trim(), project]));
  }, [realEstateProjects]);

  // Helper function to calculate tax rate for an item based on priority: item > group > default
  const getTaxRateForItem = (material: ProductionItem | undefined): number => {
    if (!material) return defaultTaxRate || 0;
    
    // Priority 1: Item-level tax rate
    if (material.taxRate !== undefined && material.taxRate > 0) {
      return material.taxRate;
    }
    
    // Priority 2: Item group tax rate
    if (material.groupId) {
      const group = itemGroups.find(g => g.id === material.groupId);
      if (group?.taxRate !== undefined && group.taxRate > 0 && group.usesDefaultTax !== false) {
        return group.taxRate;
      }
    }
    
    // Priority 3: Default tax rate
    return defaultTaxRate || 0;
  };

  const watchAllItems = useWatch({
    control: form.control,
    name: 'items',
  });
  
  const watchedAmountPaid = useWatch({
    control: form.control,
    name: 'amountPaid',
  });

  const watchedTaxMethod = useWatch({
    control: form.control,
    name: 'taxMethod',
  });

  const watchedInvoiceTaxRate = useWatch({
    control: form.control,
    name: 'invoiceTaxRate',
  });

  const watchedInvoiceDiscountPercent = useWatch({
    control: form.control,
    name: 'invoiceDiscountPercent',
  });

  const watchedInvoiceDiscountAmount = useWatch({
    control: form.control,
    name: 'invoiceDiscountAmount',
  });

  const watchedNotes = useWatch({
    control: form.control,
    name: 'notes',
  });

  const watchedRealEstateLinkMode = useWatch({
    control: form.control,
    name: 'realEstateLinkMode',
  }) || 'none';

  const watchedRealEstateProjectId = useWatch({
    control: form.control,
    name: 'realEstateProjectId',
  }) || '';

  const watchedRealEstateScope = useWatch({
    control: form.control,
    name: 'realEstateScope',
  }) || 'project';

  const watchedRealEstateAllocationMethod = useWatch({
    control: form.control,
    name: 'realEstateAllocationMethod',
  }) || 'area';

  const selectedRealEstateProject = useMemo(() => {
    return realEstateProjectsById.get(String(watchedRealEstateProjectId || '').trim());
  }, [realEstateProjectsById, watchedRealEstateProjectId]);

  const selectedProjectAllocationStats = useMemo(() => {
    const directUnits = Array.isArray(selectedRealEstateProject?.units) ? selectedRealEstateProject.units : [];
    const fallbackUnits = Array.isArray(selectedRealEstateProject?.floorDetails)
      ? selectedRealEstateProject.floorDetails.flatMap((floor) => {
          const details = Array.isArray(floor?.unitDetails) && floor.unitDetails.length > 0
            ? floor.unitDetails.map((detail) => ({
                area: Number(detail?.area || 0),
                saleValue: Number((detail as any)?.estimatedSaleValue || 0),
              }))
            : Array.from({ length: Math.max(0, Number(floor?.unitCount || 0)) }, () => ({
                area: Number(floor?.unitArea || 0),
                saleValue: Number((floor as any)?.estimatedUnitSaleValue || 0),
              }));
          return details;
        })
      : [];
    const units = directUnits.length > 0 ? directUnits : fallbackUnits;
    const manualAllocations = Array.isArray(selectedRealEstateProject?.sharedCostUnitAllocations)
      ? selectedRealEstateProject.sharedCostUnitAllocations
      : [];

    return {
      unitCount: units.length,
      totalArea: units.reduce((sum, unit) => sum + Math.max(0, Number((unit as any)?.area || 0)), 0),
      totalSaleValue: units.reduce((sum, unit) => sum + Math.max(0, Number((unit as any)?.saleValue || 0)), 0),
      manualShareTotal: manualAllocations.reduce((sum, entry) => sum + Math.max(0, Number(entry?.percentage || 0)), 0),
    };
  }, [selectedRealEstateProject]);

  const normalizeRealEstateOptionKey = useCallback((value: string) => {
    return toEnglishDigits(String(value || '').trim().toLowerCase());
  }, []);

  const getRealEstateUsageLabel = useCallback((usageType?: string) => {
    const normalizedUsage = String(usageType || '').trim();
    const usageMap: Record<string, string> = {
      warehouse: t?.warehouseLabel ?? 'مستودع',
      parking: t?.parkingLabel ?? 'موقف سيارات',
      apartments: t?.apartmentsLabel ?? 'شقق',
      commercial: t?.commercialLabel ?? 'تجاري',
      services: t?.servicesLabel ?? 'خدمات',
      mixed: t?.mixedUseLabel ?? 'متعدد الاستخدام',
      other: t?.otherLabel ?? 'أخرى',
    };
    return usageMap[normalizedUsage] || normalizedUsage;
  }, [t]);

  const realEstateFloorOptions = useMemo(() => {
    const floors = Array.isArray(selectedRealEstateProject?.floorDetails) ? selectedRealEstateProject.floorDetails : [];
    return floors.map((floor, index) => {
      const floorLabel = String(floor?.floorLabel || `الطابق ${index + 1}`).trim() || `الطابق ${index + 1}`;
      const usageLabel = getRealEstateUsageLabel(floor?.usageType);
      const unitCount = Math.max(0, Number(floor?.unitCount || 0));
      const unitArea = Math.max(0, Number(floor?.unitArea || 0));
      const helperText = [
        usageLabel,
        unitCount > 0 ? `${unitCount} ${(t?.unitsCountLabel ?? 'وحدات')}` : '',
        unitArea > 0 ? `${unitArea.toFixed(2)} م²` : '',
      ].filter(Boolean).join(' • ');

      return {
        id: String(floor?.id || `floor-${index + 1}`),
        value: floorLabel,
        label: floorLabel,
        helperText,
        unitDetails: Array.isArray(floor?.unitDetails) ? floor.unitDetails : [],
        description: String(floor?.description || '').trim(),
        notes: String(floor?.notes || '').trim(),
      };
    });
  }, [selectedRealEstateProject, getRealEstateUsageLabel, t]);

  const getRealEstatePartOptions = useCallback((floorLabel?: string) => {
    const normalizedFloor = normalizeRealEstateOptionKey(String(floorLabel || ''));
    const matchedFloor = realEstateFloorOptions.find((entry) => normalizeRealEstateOptionKey(entry.value) === normalizedFloor);
    if (!matchedFloor) return [] as Array<{ value: string; label: string }>;

    const unitOptions = matchedFloor.unitDetails
      .map((detail, detailIndex) => {
        const unitLabel = String(detail?.unitLabel || '').trim() || `${t?.apartmentsLabel ?? 'وحدة'} ${detailIndex + 1}`;
        const notes = String(detail?.notes || '').trim();
        const area = Math.max(0, Number(detail?.area || 0));
        const label = [
          unitLabel,
          notes,
          area > 0 ? `${area.toFixed(2)} م²` : '',
        ].filter(Boolean).join(' — ');
        return { value: unitLabel, label };
      })
      .filter((entry) => entry.value);

    if (unitOptions.length > 0) {
      return unitOptions;
    }

    return [matchedFloor.description, matchedFloor.notes]
      .filter(Boolean)
      .map((entry) => ({ value: entry, label: entry }));
  }, [normalizeRealEstateOptionKey, realEstateFloorOptions, t]);

  useEffect(() => {
    const projectName = String(selectedRealEstateProject?.name || '');
    if (String(form.getValues('realEstateProjectName') || '') !== projectName) {
      form.setValue('realEstateProjectName', projectName, { shouldDirty: false, shouldValidate: false });
    }

    if (watchedRealEstateLinkMode === 'none') {
      if (form.getValues('realEstateFloorLabel')) {
        form.setValue('realEstateFloorLabel', '', { shouldDirty: false, shouldValidate: false });
      }
      if (form.getValues('realEstatePartLabel')) {
        form.setValue('realEstatePartLabel', '', { shouldDirty: false, shouldValidate: false });
      }
      return;
    }

    if (watchedRealEstateScope === 'project') {
      if (form.getValues('realEstateFloorLabel')) {
        form.setValue('realEstateFloorLabel', '', { shouldDirty: false, shouldValidate: false });
      }
      if (form.getValues('realEstatePartLabel')) {
        form.setValue('realEstatePartLabel', '', { shouldDirty: false, shouldValidate: false });
      }
      return;
    }

    const currentFloorLabel = String(form.getValues('realEstateFloorLabel') || '').trim();
    const hasMatchingFloor = realEstateFloorOptions.some((entry) => normalizeRealEstateOptionKey(entry.value) === normalizeRealEstateOptionKey(currentFloorLabel));
    const resolvedFloorLabel = hasMatchingFloor ? currentFloorLabel : (realEstateFloorOptions[0]?.value || currentFloorLabel);

    if (resolvedFloorLabel !== currentFloorLabel) {
      form.setValue('realEstateFloorLabel', resolvedFloorLabel, { shouldDirty: false, shouldValidate: false });
    }

    if (watchedRealEstateScope !== 'part') {
      if (form.getValues('realEstatePartLabel')) {
        form.setValue('realEstatePartLabel', '', { shouldDirty: false, shouldValidate: false });
      }
      return;
    }

    const partOptions = getRealEstatePartOptions(resolvedFloorLabel);
    const currentPartLabel = String(form.getValues('realEstatePartLabel') || '').trim();
    const hasMatchingPart = partOptions.some((entry) => normalizeRealEstateOptionKey(entry.value) === normalizeRealEstateOptionKey(currentPartLabel));
    const resolvedPartLabel = hasMatchingPart ? currentPartLabel : (partOptions[0]?.value || currentPartLabel);

    if (resolvedPartLabel !== currentPartLabel) {
      form.setValue('realEstatePartLabel', resolvedPartLabel, { shouldDirty: false, shouldValidate: false });
    }
  }, [watchedRealEstateLinkMode, watchedRealEstateScope, selectedRealEstateProject, realEstateFloorOptions, getRealEstatePartOptions, normalizeRealEstateOptionKey, form]);

  useEffect(() => {
    if (watchedRealEstateLinkMode !== 'line-items') {
      return;
    }

    const defaultFloorLabel = realEstateFloorOptions[0]?.value || '';
    setGridItems((prev) => {
      let changed = false;
      const next = prev.map((item) => {
        const nextScope = item.realEstateScope || 'project';
        const resolvedAllocationMethod = nextScope === 'project'
          ? (item.realEstateAllocationMethod || watchedRealEstateAllocationMethod || 'area')
          : undefined;
        const currentFloorLabel = String(item.realEstateFloorLabel || '').trim();
        const hasMatchingFloor = realEstateFloorOptions.some((entry) => normalizeRealEstateOptionKey(entry.value) === normalizeRealEstateOptionKey(currentFloorLabel));
        const resolvedFloorLabel = nextScope === 'project'
          ? ''
          : (hasMatchingFloor ? currentFloorLabel : (defaultFloorLabel || currentFloorLabel));
        const partOptions = getRealEstatePartOptions(resolvedFloorLabel);
        const currentPartLabel = String(item.realEstatePartLabel || '').trim();
        const hasMatchingPart = partOptions.some((entry) => normalizeRealEstateOptionKey(entry.value) === normalizeRealEstateOptionKey(currentPartLabel));
        const resolvedPartLabel = nextScope === 'part'
          ? (hasMatchingPart ? currentPartLabel : (partOptions[0]?.value || currentPartLabel))
          : '';

        if (
          item.realEstateProjectId !== (watchedRealEstateProjectId || '')
          || item.realEstateProjectName !== String(selectedRealEstateProject?.name || '')
          || item.realEstateScope !== nextScope
          || item.realEstateFloorLabel !== resolvedFloorLabel
          || item.realEstatePartLabel !== resolvedPartLabel
          || item.realEstateAllocationMethod !== resolvedAllocationMethod
        ) {
          changed = true;
        }

        return {
          ...item,
          realEstateProjectId: watchedRealEstateProjectId || '',
          realEstateProjectName: String(selectedRealEstateProject?.name || ''),
          realEstateScope: nextScope,
          realEstateFloorLabel: resolvedFloorLabel,
          realEstatePartLabel: resolvedPartLabel,
          realEstateAllocationMethod: resolvedAllocationMethod,
        };
      });

      return changed ? next : prev;
    });
  }, [watchedRealEstateLinkMode, watchedRealEstateProjectId, watchedRealEstateAllocationMethod, selectedRealEstateProject, realEstateFloorOptions, getRealEstatePartOptions, normalizeRealEstateOptionKey]);

  const orderActivityLog = useMemo(() => {
    const entries = Array.isArray(existingOrder?.activityLog) ? existingOrder.activityLog : [];
    return [...entries].sort((left, right) => {
      const leftTime = new Date(left.at || 0).getTime();
      const rightTime = new Date(right.at || 0).getTime();
      return rightTime - leftTime;
    });
  }, [existingOrder?.activityLog]);

  const formatActivityMessageForDisplay = (message?: string) => {
    const rawMessage = String(message || '').trim();
    if (!rawMessage) return '-';

    // Legacy entries used to embed full before/after JSON snapshots.
    const summaryOnly = rawMessage.split('قبل التحديث:')[0].trim();
    return summaryOnly || rawMessage;
  };

  const watchedWarehouseId = useWatch({
    control: form.control,
    name: 'warehouseId',
  });

  const watchedCurrencyCode = useWatch({
    control: form.control,
    name: 'currencyCode',
  });

  const watchedBaseCurrencyCode = useWatch({
    control: form.control,
    name: 'baseCurrencyCode',
  });

  const watchedExchangeRate = useWatch({
    control: form.control,
    name: 'exchangeRate',
  });

  const watchedRateSource = useWatch({
    control: form.control,
    name: 'rateSource',
  });

  const watchedIsAutoRate = useWatch({
    control: form.control,
    name: 'isAutoRate',
  });

  const selectedCurrency = useMemo(() => currencies.find((c) => c.code === watchedCurrencyCode) || currencies.find((c) => c.isDefault) || baseCurrency, [currencies, watchedCurrencyCode, baseCurrency]);
  const baseCurrencyEntry = useMemo(() => currencies.find((c) => c.code === (watchedBaseCurrencyCode || defaultBaseCurrencyCode)) || baseCurrency, [currencies, watchedBaseCurrencyCode, defaultBaseCurrencyCode, baseCurrency]);
  const displayCurrencySymbol = selectedCurrency?.symbol || currencySymbol;
  const baseCurrencySymbol = baseCurrencyEntry?.symbol || currencySymbol;
  const effectiveExchangeRate = watchedCurrencyCode === (watchedBaseCurrencyCode || defaultBaseCurrencyCode)
    ? 1
    : (Number(watchedExchangeRate) || 1);

  const convertAmountByRates = (amount: number, fromCurrency: string, toCurrency: string) => {
    if (!Number.isFinite(amount)) return 0;
    if (!fromCurrency || !toCurrency || fromCurrency === toCurrency) return amount;

    const fromEntry = currencies.find((entry) => entry.code === fromCurrency);
    const toEntry = currencies.find((entry) => entry.code === toCurrency);
    if (!fromEntry || !toEntry) return amount;

    const fromRate = Number(fromEntry.exchangeRate || 0);
    const toRate = Number(toEntry.exchangeRate || 0);
    if (fromRate <= 0 || toRate <= 0) return amount;

    const amountInBase = amount / fromRate;
    return amountInBase * toRate;
  };

  const availableIncomingChecks = useMemo(() => {
    const normalizedSupplierId = String(selectedPartyInfo?.id || '').trim();
    const currentOrderId = existingOrder?.id || '';
    return incomingChecks.filter((entry) => {
      if (entry.status !== 'pending') return false;
      
      // Filter by reservation status
      const reservationStatus = entry.reservationStatus || 'available';
      if (reservationStatus === 'available') {
        // Available checks can always be used
        return true;
      }
      if (reservationStatus === 'reserved') {
        // Reserved checks can only be used by the PO that reserved them (edit mode)
        return currentOrderId && entry.reservedByPurchaseOrderId === currentOrderId;
      }
      if (reservationStatus === 'endorsed') {
        // Endorsed checks can only be used if they're endorsed to the same supplier
        return entry.endorsedToType === 'supplier' && entry.endorsedToId === normalizedSupplierId;
      }
      
      return false;
    });
  }, [incomingChecks, selectedPartyInfo?.id, existingOrder?.id]);

  // Keep FX fields in sync with the configured currency table.
  useEffect(() => {
    if (mode === 'edit' && existingOrder) return;
    if (!watchedCurrencyCode) return;
    const baseCode = defaultBaseCurrencyCode;
    if (watchedCurrencyCode === baseCode) {
      form.setValue('baseCurrencyCode', baseCode, { shouldDirty: true });
      form.setValue('exchangeRate', 1, { shouldDirty: true });
      form.setValue('isAutoRate', true, { shouldDirty: true });
      if (!form.getValues('rateDate')) {
        form.setValue('rateDate', defaultRateDate, { shouldDirty: true });
      }
      return;
    }

    const selectedRate = Number(currencies.find((c) => c.code === watchedCurrencyCode)?.exchangeRate || 0);
    form.setValue('baseCurrencyCode', baseCode, { shouldDirty: true });
    form.setValue('exchangeRate', Number.isFinite(selectedRate) && selectedRate > 0 ? selectedRate : 1, { shouldDirty: true });
    form.setValue('isAutoRate', true, { shouldDirty: true });
    if (!form.getValues('rateDate')) {
      form.setValue('rateDate', defaultRateDate, { shouldDirty: true });
    }
  }, [mode, existingOrder, watchedCurrencyCode, defaultBaseCurrencyCode, defaultRateDate, form, currencies]);

  // Auto-calculate amountPaid from payment methods in mixed mode
  useEffect(() => {
    if (paymentTabMode === 'mixed' && paymentMethods.length > 0) {
      const totalAmount = paymentMethods.reduce((sum, method) => {
        if (method.method === 'credit') return sum; // Credit doesn't count as immediate payment
        if (method.method === 'check' && Array.isArray(method.incomingCheckIds) && method.incomingCheckIds.length > 0) {
          // For incoming checks, sum the selected check amounts
          const checkTotal = availableIncomingChecks
            .filter(check => method.incomingCheckIds?.includes(check.id))
            .reduce((acc, check) => {
              const amount = Number(check.amount || 0);
              const fromCurrency = check.currency || defaultBaseCurrencyCode;
              const toCurrency = method.currency || watchedCurrencyCode || defaultBaseCurrencyCode;
              return acc + convertAmountByRates(amount, fromCurrency, toCurrency);
            }, 0);
          return sum + checkTotal;
        }
        if (method.method === 'check' && (!Array.isArray(method.incomingCheckIds) || method.incomingCheckIds.length === 0)) {
          // For issued checks, amount comes from the check details in paymentMethods
          return sum + (Number(method.amount || 0));
        }
        // For cash and bank_transfer, add the amount directly
        return sum + (Number(method.amount || 0));
      }, 0);
      
      form.setValue('amountPaid', totalAmount, { shouldDirty: true, shouldValidate: false });
    }
  }, [paymentMethods, paymentTabMode, watchedCurrencyCode, form, defaultBaseCurrencyCode, availableIncomingChecks]);

  const getLineDiscountAmount = (
    quantity: number,
    unitPrice: number,
    percent?: number,
    amount?: number
  ) => {
    const lineSubtotal = Number(quantity || 0) * Number(unitPrice || 0);
    const percentValue = Number(percent || 0);
    const amountValue = Number(amount || 0);
    const discountFromPercent = percentValue > 0 ? (lineSubtotal * percentValue) / 100 : 0;
    const discount = discountFromPercent > 0 ? discountFromPercent : amountValue;
    return Math.min(lineSubtotal, discount);
  };

  const calculateLineTotal = (item: z.infer<typeof purchaseOrderSchema>["items"][number]) => {
    const qty = Number(item.quantity || 0);
    const price = Number(item.unitPrice || 0);
    const discountAmount = getLineDiscountAmount(qty, price, item.lineDiscountPercent, item.lineDiscountAmount);
    return Math.max(0, qty * price - discountAmount);
  };

  const handleLineTotalChange = (index: number, rawTotal: string) => {
    const desiredTotal = Number(rawTotal);
    const current = gridItems[index];
    if (!current || !Number.isFinite(desiredTotal)) return;

    const qty = Math.max(0, Number(current.quantity || 0));
    const percent = Math.max(0, Math.min(100, Number(current.lineDiscountPercent || 0)));
    const amount = Math.max(0, Number(current.lineDiscountAmount || 0));
    const factor = qty * (1 - percent / 100);

    if (factor <= 0) {
      toast({
        title: tGlobal?.error || 'خطأ',
        description: t?.lineTotalCannotResolveUnitPrice ?? 'لا يمكن احتساب سعر الوحدة عند كمية صفر أو خصم 100%.',
        variant: 'destructive',
      });
      return;
    }

    const nextUnitPrice = Math.max(0, (Math.max(0, desiredTotal) + amount) / factor);
    const newItems = [...gridItems];
    newItems[index].unitPrice = Number(nextUnitPrice.toFixed(6));
    setGridItems(newItems);
  };

  const itemsWithDetails = useMemo(() => {
    if (!watchAllItems) return [];
    return watchAllItems.filter((item) => !isEffectivelyEmptyPurchaseItem(item)).map((item) => {
      const material = materialsById.get(item.materialId);
      const headerWarehouseId = isWarehouseEnabled ? (watchedWarehouseId || defaultWarehouseId || '') : '';
      const warehouseId = isWarehouseEnabled ? headerWarehouseId : '';
      const shelfId = isWarehouseEnabled ? (item.shelfId || defaultShelfId || '') : '';
      const itemTaxRate = getTaxRateForItem(material);
      const subtotal = item.quantity * item.unitPrice;
      const lineDiscount = getLineDiscountAmount(
        item.quantity,
        item.unitPrice,
        item.lineDiscountPercent,
        item.lineDiscountAmount
      );
      const lineTotal = Math.max(0, subtotal - lineDiscount);
      const itemTaxAmount = (lineTotal * itemTaxRate) / 100;
      
      return {
        ...item,
        name: material?.name || 'Unknown Item',
        warehouseId,
        shelfId,
        lineDiscountPercent: item.lineDiscountPercent ?? 0,
        lineDiscountAmount: item.lineDiscountAmount ?? 0,
        lineDiscount,
        bonus: item.bonus ?? 0,
        taxRate: itemTaxRate,
        itemTaxAmount,
        total: lineTotal,
      };
    });
  }, [watchAllItems, materialsById, isWarehouseEnabled, watchedWarehouseId, defaultWarehouseId, defaultShelfId, getTaxRateForItem, getLineDiscountAmount]);

  const subTotal = useMemo(() => {
    return itemsWithDetails.reduce((sum, item) => sum + item.total, 0);
  }, [itemsWithDetails]);

  const invoiceDiscount = useMemo(() => {
    const percentValue = Number(watchedInvoiceDiscountPercent || 0);
    const amountValue = Number(watchedInvoiceDiscountAmount || 0);
    const discountFromPercent = percentValue > 0 ? (subTotal * percentValue) / 100 : 0;
    const discount = discountFromPercent > 0 ? discountFromPercent : amountValue;
    return Math.min(subTotal, discount);
  }, [subTotal, watchedInvoiceDiscountPercent, watchedInvoiceDiscountAmount]);

  // Calculate tax amount based on method
  const taxAmount = useMemo(() => {
    if (watchedTaxMethod === 'invoice-level' && watchedInvoiceTaxRate) {
      return ((subTotal - invoiceDiscount) * watchedInvoiceTaxRate) / 100;
    }
    if (watchedTaxMethod === 'line-level') {
      // Sum per-item taxes calculated based on each item's priority tax rate
      return itemsWithDetails.reduce((sum, item) => sum + (item.itemTaxAmount || 0), 0);
    }
    if (watchedTaxMethod === 'tax-inclusive' || watchedTaxMethod === 'tax-exempt') {
      return 0;
    }
    return 0;
  }, [subTotal, watchedTaxMethod, watchedInvoiceTaxRate, itemsWithDetails]);

  const grandTotal = Math.max(0, subTotal - invoiceDiscount) + taxAmount;
  const amountDue = Math.max(0, grandTotal - watchedAmountPaid);
  const activeSinglePaymentMethod = useMemo(() => {
    return paymentMethods[0] || {
      method: 'credit',
      amount: 0,
      currency: watchedCurrencyCode || defaultBaseCurrencyCode,
      checkSource: 'issued',
      incomingCheckIds: [],
      checkNumber: '',
      checkDate: '',
      bankId: '',
      bankName: '',
      reference: '',
    };
  }, [paymentMethods, watchedCurrencyCode, defaultBaseCurrencyCode]);

  useEffect(() => {
    setPaymentMethods((prev) => {
      const orderCurrency = watchedCurrencyCode || defaultBaseCurrencyCode;

      if (paymentTabMode === 'mixed') {
        if (prev.length > 0) return prev;
        return [{ method: 'cash', amount: Number(watchedAmountPaid || 0), currency: orderCurrency }];
      }

      if (paymentTabMode === 'credit') {
        return [{
          method: 'credit',
          amount: 0,
          currency: orderCurrency,
          checkSource: undefined,
          incomingCheckIds: [],
          checkNumber: '',
          checkDate: '',
          bankId: '',
          bankName: '',
          reference: '',
        }];
      }

      const first = prev[0] || {};

      if (
        paymentTabMode === 'check' &&
        (first.checkSource || 'issued') === 'issued' &&
        issuedChecks.length > 0
      ) {
        return prev;
      }

      return [{
        ...first,
        method: paymentTabMode,
        amount: Number(watchedAmountPaid || 0),
        currency: orderCurrency,
        checkSource: paymentTabMode === 'check' ? (first.checkSource || 'issued') : undefined,
        incomingCheckIds: paymentTabMode === 'check' ? (Array.isArray(first.incomingCheckIds) ? first.incomingCheckIds : []) : [],
      }];
    });
  }, [paymentTabMode, watchedAmountPaid, watchedCurrencyCode, defaultBaseCurrencyCode, issuedChecks.length]);

  useEffect(() => {
    if (paymentTabMode === 'credit' && Number(watchedAmountPaid || 0) !== 0) {
      form.setValue('amountPaid', 0, { shouldDirty: true, shouldValidate: true });
    }
  }, [paymentTabMode, watchedAmountPaid, form]);

  useEffect(() => {
    if (!defaultCashAccount && !defaultBankAccount) return;
    if (paymentTabMode === 'mixed') return;

    setPaymentMethods((prev) => {
      if (!prev[0]) return prev;

      const first = prev[0];
      if (first.method === 'credit') return prev;

      const isBankLike = first.method === 'bank_transfer' || first.method === 'check';
      const target = isBankLike ? defaultBankAccount : defaultCashAccount;
      if (!target) return prev;

      if (first.bankId === target.id && first.bankName === target.name) return prev;

      const next = [...prev];
      next[0] = {
        ...first,
        bankId: target.id,
        bankName: target.name,
      };
      return next;
    });
  }, [paymentTabMode, defaultCashAccount, defaultBankAccount]);

  const singleIncomingChecksTotal = useMemo(() => {
    if (paymentTabMode !== 'check' || activeSinglePaymentMethod.checkSource !== 'incoming') return 0;
    const selectedIds = Array.isArray(activeSinglePaymentMethod.incomingCheckIds) ? activeSinglePaymentMethod.incomingCheckIds : [];
    if (selectedIds.length === 0) return 0;
    const orderCurrency = watchedCurrencyCode || defaultBaseCurrencyCode;
    return availableIncomingChecks
      .filter((entry) => selectedIds.includes(entry.id))
      .reduce((sum, entry) => {
        const checkAmount = Number(entry.amount || 0);
        const checkCurrency = entry.currency || defaultBaseCurrencyCode;
        return sum + convertAmountByRates(checkAmount, checkCurrency, orderCurrency);
      }, 0);
  }, [paymentTabMode, activeSinglePaymentMethod, availableIncomingChecks, watchedCurrencyCode, defaultBaseCurrencyCode, convertAmountByRates]);

  useEffect(() => {
    if (paymentTabMode !== 'check') return;
    if ((activeSinglePaymentMethod.checkSource || 'issued') !== 'incoming') return;

    const normalizedTotal = Number(singleIncomingChecksTotal.toFixed(2));

    if (Math.abs(Number(watchedAmountPaid || 0) - normalizedTotal) > 0.0001) {
      form.setValue('amountPaid', normalizedTotal, { shouldDirty: true, shouldValidate: true });
    }

    setPaymentMethods((prev) => {
      if (!prev[0]) return prev;
      if (Math.abs(Number(prev[0].amount || 0) - normalizedTotal) <= 0.0001) return prev;
      const next = [...prev];
      next[0] = { ...next[0], amount: normalizedTotal };
      return next;
    });
  }, [paymentTabMode, activeSinglePaymentMethod.checkSource, singleIncomingChecksTotal, watchedAmountPaid, form]);

  const syncIssuedChecksToPaymentMethods = (rows: IssuedCheckRow[]) => {
    const orderCurrency = watchedCurrencyCode || defaultBaseCurrencyCode;
    const mapped = rows.map((row, index) => ({
      id: row.id || `issued-check-${index + 1}`,
      method: 'check' as const,
      amount: Number(row.amount || 0),
      currency: row.currency || orderCurrency,
      checkSource: 'issued' as const,
      incomingCheckIds: [],
      checkNumber: row.checkNumber || undefined,
      checkDate: row.checkDate || undefined,
      bankId: row.bankId || undefined,
      bankName: row.bankName || undefined,
      reference: '',
    }));

    if (mapped.length > 0) {
      setPaymentMethods(mapped);
      const totalPaid = mapped.reduce((sum, method) => {
        const amount = Number(method.amount || 0);
        const fromCurrency = method.currency || orderCurrency;
        return sum + convertAmountByRates(amount, fromCurrency, orderCurrency);
      }, 0);
      form.setValue('amountPaid', Number(totalPaid.toFixed(2)), { shouldDirty: true, shouldValidate: true });
      return;
    }

    setPaymentMethods([{ method: 'check', amount: undefined, currency: orderCurrency, checkSource: 'issued', incomingCheckIds: [] }]);
    form.setValue('amountPaid', 0, { shouldDirty: true, shouldValidate: true });
  };

  const itemGridSummary = useMemo(() => {
    const populatedItems = itemsWithDetails.filter((item) => {
      return Boolean(item.materialId)
        || Number(item.quantity || 0) > 0
        || Number(item.unitPrice || 0) > 0
        || Number(item.bonus || 0) > 0
        || Number(item.lineDiscountAmount || 0) > 0
        || Number(item.lineDiscountPercent || 0) > 0;
    });

    return {
      itemCount: populatedItems.length,
      totalQuantity: populatedItems.reduce((sum, item) => sum + Number(item.quantity || 0), 0),
      totalBonus: populatedItems.reduce((sum, item) => sum + Number(item.bonus || 0), 0),
      totalLineDiscount: populatedItems.reduce((sum, item) => sum + Number(item.lineDiscount || 0), 0),
      totalBeforeDiscount: populatedItems.reduce((sum, item) => sum + (Number(item.quantity || 0) * Number(item.unitPrice || 0)), 0),
    };
  }, [itemsWithDetails]);

  const normalizeSearchText = (value: string) => {
    return value
      .toLowerCase()
      .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '')
      .replace(/[إأآٱ]/g, 'ا')
      .replace(/ى/g, 'ي')
      .replace(/ؤ/g, 'و')
      .replace(/ئ/g, 'ي')
      .replace(/ة/g, 'ه')
      .replace(/[^\p{L}\p{N}]+/gu, '');
  };

  const matchesMaterialSearch = (material: ProductionItem, query: string) => {
    const trimmed = query.trim();
    if (!trimmed) return true;

    const tokens = trimmed
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);

    if (tokens.length === 0) return true;

    const normalizedName = normalizeSearchText(material.name || '');
    const normalizedNumber = normalizeSearchText(String(material.itemNumber || material.id || ''));
    const normalizedBarcode = normalizeSearchText(material.barcode || '');
    const normalizedExtra = (material.additionalBarcodes || [])
      .map((code) => normalizeSearchText(code || ''))
      .join(' ');
    const normalizedAdditionalDetails = normalizeSearchText(material.additionalDetails || '');

    return tokens.every((token) =>
      normalizedName.includes(token) ||
      normalizedNumber.includes(token) ||
      normalizedBarcode.includes(token) ||
      normalizedExtra.includes(token) ||
      normalizedAdditionalDetails.includes(token)
    );
  };

  const filteredMaterials = useMemo(
    () => allMaterials.filter((material) => matchesMaterialSearch(material, itemSelectQuery)),
    [allMaterials, itemSelectQuery]
  );

  const ITEM_PICKER_ROW_HEIGHT = 52;
  const ITEM_PICKER_VIEWPORT_HEIGHT = 420;
  const ITEM_PICKER_OVERSCAN = 8;
  const normalizedItemPickerQuery = String(itemPickerQuery || '').trim();

  const pickerMatchedMaterials = useMemo(() => {
    if (!normalizedItemPickerQuery) return allMaterials;
    return allMaterials.filter((material) => matchesMaterialSearch(material, normalizedItemPickerQuery));
  }, [allMaterials, normalizedItemPickerQuery]);

  const pickerVisibleCount = Math.ceil(ITEM_PICKER_VIEWPORT_HEIGHT / ITEM_PICKER_ROW_HEIGHT);
  const pickerStartIndex = Math.max(0, Math.floor(itemPickerScrollTop / ITEM_PICKER_ROW_HEIGHT) - ITEM_PICKER_OVERSCAN);
  const pickerEndIndex = Math.min(
    pickerMatchedMaterials.length,
    pickerStartIndex + pickerVisibleCount + ITEM_PICKER_OVERSCAN * 2
  );

  const filteredPickerMaterials = useMemo(
    () => pickerMatchedMaterials.slice(pickerStartIndex, pickerEndIndex),
    [pickerMatchedMaterials, pickerStartIndex, pickerEndIndex]
  );

  const pickerTopSpacerHeight = pickerStartIndex * ITEM_PICKER_ROW_HEIGHT;
  const pickerBottomSpacerHeight = Math.max(0, (pickerMatchedMaterials.length - pickerEndIndex) * ITEM_PICKER_ROW_HEIGHT);

  useEffect(() => {
    if (!showItemPicker) return;
    setItemPickerScrollTop(0);
    if (itemPickerScrollRef.current) {
      itemPickerScrollRef.current.scrollTop = 0;
    }
  }, [showItemPicker, normalizedItemPickerQuery]);

  const getOrderTaxRateDecimal = (order: PurchaseOrder, item: PurchaseOrderItem) => {
    const lineSubtotal = Math.max(0, Number(item.total || (Number(item.quantity || 0) * Number(item.unitPrice || 0))));

    if (order.taxMethod === 'line-level') {
      const explicitRate = Number(item.taxRate || 0) / 100;
      if (Number.isFinite(explicitRate) && explicitRate > 0) return explicitRate;

      const lineTaxAmount = Number(item.taxAmount || 0);
      if (lineSubtotal > 0 && Number.isFinite(lineTaxAmount) && lineTaxAmount > 0) {
        return lineTaxAmount / lineSubtotal;
      }
      return 0;
    }

    if (order.taxMethod === 'invoice-level') {
      const taxableBase = Math.max(0, Number(order.subTotal || 0) - Number(order.invoiceDiscountAmount || 0));
      const totalTax = Number(order.taxAmount || 0);
      if (taxableBase > 0 && Number.isFinite(totalTax) && totalTax > 0) {
        return totalTax / taxableBase;
      }
      return 0;
    }

    return 0;
  };

  const normalizePurchaseUnitPriceForCurrentTax = (
    order: PurchaseOrder,
    item: PurchaseOrderItem,
    targetTaxMethod: 'tax-inclusive' | 'invoice-level' | 'line-level' | 'tax-exempt'
  ) => {
    const sourceMethod = order.taxMethod || 'tax-inclusive';
    const unitPrice = Number(item.unitPrice || 0);
    if (!Number.isFinite(unitPrice) || unitPrice <= 0) return 0;

    const taxRate = getOrderTaxRateDecimal(order, item);
    const addTaxToPrice = targetTaxMethod === 'tax-inclusive' && (sourceMethod === 'line-level' || sourceMethod === 'invoice-level');
    const removeTaxFromPrice = targetTaxMethod !== 'tax-inclusive' && sourceMethod === 'tax-inclusive';

    if (addTaxToPrice && taxRate > 0) {
      return unitPrice * (1 + taxRate);
    }

    if (removeTaxFromPrice && taxRate > 0) {
      return unitPrice / (1 + taxRate);
    }

    return unitPrice;
  };

  const purchasePriceHistoryRows = useMemo(() => {
    const rows: Array<{
      materialId: string;
      materialName: string;
      orderId: string;
      orderNumber: string;
      orderDate: string;
      supplierName: string;
      quantity: number;
      rawUnitPrice: number;
      adjustedUnitPrice: number;
      taxMethod: string;
      taxRatePercent: number;
      currencyCode: string;
    }> = [];

    purchaseOrders
      .filter((order) => order.status !== 'cancelled' && (order.postingStatus || 'saved') !== 'draft')
      .forEach((order) => {
        (order.items || []).forEach((item) => {
          const materialId = String(item.materialId || '').trim();
          if (!materialId) return;

          const rawUnitPrice = Number(item.unitPrice || 0);
          const adjustedUnitPrice = normalizePurchaseUnitPriceForCurrentTax(order, item, watchedTaxMethod || 'tax-inclusive');
          const taxRatePercent = getOrderTaxRateDecimal(order, item) * 100;

          rows.push({
            materialId,
            materialName: allMaterials.find((material) => material.id === materialId)?.name || materialId,
            orderId: order.id,
            orderNumber: order.orderNumber,
            orderDate: order.date,
            supplierName: order.supplierName,
            quantity: Number(item.quantity || 0),
            rawUnitPrice: Number.isFinite(rawUnitPrice) ? rawUnitPrice : 0,
            adjustedUnitPrice: Number.isFinite(adjustedUnitPrice) ? adjustedUnitPrice : 0,
            taxMethod: order.taxMethod || 'tax-inclusive',
            taxRatePercent: Number.isFinite(taxRatePercent) ? taxRatePercent : 0,
            currencyCode: String(order.currencyCode || watchedCurrencyCode || defaultBaseCurrencyCode || '').trim() || 'USD',
          });
        });
      });

    return rows.sort((a, b) => {
      const dateDiff = new Date(b.orderDate || 0).getTime() - new Date(a.orderDate || 0).getTime();
      if (dateDiff !== 0) return dateDiff;
      return b.orderNumber.localeCompare(a.orderNumber);
    });
  }, [purchaseOrders, allMaterials, watchedTaxMethod, watchedCurrencyCode, defaultBaseCurrencyCode]);

  const latestPurchasePriceByMaterial = useMemo(() => {
    const map = new Map<string, number>();
    purchasePriceHistoryRows.forEach((entry) => {
      if (map.has(entry.materialId)) return;
      map.set(entry.materialId, Number(entry.adjustedUnitPrice || 0));
    });
    return map;
  }, [purchasePriceHistoryRows]);

  // Maps materialId::currencyCode → latest adjusted price for that currency

  const latestComparablePurchasePriceByMaterial = useMemo(() => {
    const map = new Map<string, number>();
    purchasePriceHistoryRows.forEach((entry) => {
      if (existingOrder?.id && entry.orderId === existingOrder.id) return;
      if (map.has(entry.materialId)) return;
      map.set(entry.materialId, Number(entry.adjustedUnitPrice || 0));
    });
    return map;
  }, [purchasePriceHistoryRows, existingOrder?.id]);

  const selectedMaterialPurchaseHistory = useMemo(() => {
    if (!purchasePriceDialogMaterialId) return [];
    return purchasePriceHistoryRows.filter((entry) => entry.materialId === purchasePriceDialogMaterialId).slice(0, 100);
  }, [purchasePriceHistoryRows, purchasePriceDialogMaterialId]);

  const selectedMaterialNameForHistory = useMemo(() => {
    if (!purchasePriceDialogMaterialId) return '';
    return allMaterials.find((material) => material.id === purchasePriceDialogMaterialId)?.name || purchasePriceDialogMaterialId;
  }, [allMaterials, purchasePriceDialogMaterialId]);

  const getTaxMethodLabel = (method: string) => {
    if (method === 'invoice-level') return t?.invoiceLevelTax ?? 'ضريبة على الفاتورة';
    if (method === 'line-level') return t?.lineLevelTax ?? 'ضريبة على كل سطر';
    if (method === 'tax-exempt') return t?.taxExempt ?? 'معفاة من الضريبة';
    return t?.taxInclusive ?? 'السعر شامل الضريبة';
  };

  const getPreferredPurchasePrice = (material: ProductionItem, currencyCode?: string) => {
    const targetCurrency = currencyCode || watchedCurrencyCode || defaultBaseCurrencyCode;

    // Find the latest purchase entry for this material regardless of currency
    const latestEntry = purchasePriceHistoryRows.find((entry) => entry.materialId === material.id);
    if (!latestEntry) return 0;

    const price = Number(latestEntry.adjustedUnitPrice || 0);
    if (!Number.isFinite(price) || price <= 0) return 0;

    // If the last purchase was in the same currency as the current invoice — return as-is
    if (!targetCurrency || latestEntry.currencyCode === targetCurrency) return price;

    // Otherwise convert using stored exchange rates (amount / fromRate * toRate)
    const converted = convertAmountByRates(price, latestEntry.currencyCode, targetCurrency);
    return Number.isFinite(converted) && converted > 0 ? converted : price;
  };

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

    const closeMenu = () => setItemContextMenu(null);
    window.addEventListener('click', closeMenu);
    window.addEventListener('scroll', closeMenu, true);

    return () => {
      window.removeEventListener('click', closeMenu);
      window.removeEventListener('scroll', closeMenu, true);
    };
  }, [itemContextMenu]);

  const getMaterialPurchasePricing = (material: ProductionItem) => {
    const primaryPrice = getPreferredPurchasePrice(material, watchedCurrencyCode || defaultBaseCurrencyCode);
    const firstSecondary = Array.isArray(material.secondaryUnits) && material.secondaryUnits.length > 0
      ? material.secondaryUnits[0]
      : undefined;
    const conversionQty = Number(firstSecondary?.quantity ?? material.secondaryUnitQuantity ?? 0);
    const explicitSecondaryPrice = firstSecondary?.price;
    const secondaryPrice = Number.isFinite(Number(explicitSecondaryPrice))
      ? Number(explicitSecondaryPrice)
      : (typeof material.secondaryUnitPrice === 'number'
          ? material.secondaryUnitPrice
          : (conversionQty > 0 ? primaryPrice / conversionQty : undefined));

    return {
      primaryPrice,
      secondaryPrice: typeof secondaryPrice === 'number' && Number.isFinite(secondaryPrice) ? secondaryPrice : undefined,
    };
  };

  const getSecondaryVolumeOptions = (material: ProductionItem, primaryPrice: number) => {
    const fromArray = Array.isArray(material.secondaryUnits)
      ? material.secondaryUnits
          .map((entry, index) => {
            const unitLabel = String(entry?.unit || '').trim();
            if (!unitLabel) return null;
            const quantity = Number(entry?.quantity || 0);
            const explicit = Number(entry?.price);
            const computedPrice = Number.isFinite(explicit)
              ? explicit
              : (quantity > 0 ? (primaryPrice / quantity) : primaryPrice);
            return {
              key: `secondary-${index}`,
              label: unitLabel,
              price: computedPrice,
              barcode: String(entry?.barcode || '').trim(),
            };
          })
          .filter((entry): entry is { key: string; label: string; price: number; barcode: string } => !!entry)
      : [];

    if (fromArray.length > 0) return fromArray;

    const legacyLabel = String(material.secondaryUnit || '').trim();
    if (!legacyLabel) return [];
    const qty = Number(material.secondaryUnitQuantity || 0);
    const price = typeof material.secondaryUnitPrice === 'number'
      ? Number(material.secondaryUnitPrice)
      : (qty > 0 ? (primaryPrice / qty) : primaryPrice);
    return [{ key: 'legacy-secondary', label: legacyLabel, price, barcode: String(material.secondaryBarcode || '').trim() }];
  };

  const resolveMaterialByBarcode = (barcode: string) => {
    const normalized = barcode.trim();
    for (const material of allMaterials) {
      const primaryBarcodes = [material.barcode, ...(material.additionalBarcodes || [])].filter(Boolean);
      const isPrimary = primaryBarcodes.includes(normalized);
      const pricing = getMaterialPurchasePricing(material);
      const secondaryOptions = getSecondaryVolumeOptions(material, pricing.primaryPrice);
      const matchedSecondary = secondaryOptions.find((option) => option.barcode && option.barcode === normalized);
      const isSecondary = material.secondaryBarcode === normalized || !!matchedSecondary;
      if (!isPrimary && !isSecondary) continue;

      const primaryPrice = pricing.primaryPrice;
      const secondaryPrice = typeof pricing.secondaryPrice === 'number' ? pricing.secondaryPrice : primaryPrice;

      return {
        material,
        unitPrice: isSecondary ? Number(matchedSecondary?.price ?? secondaryPrice) : primaryPrice,
        unitType: isSecondary ? 'secondary' : 'primary',
        matchedSecondaryKey: matchedSecondary?.key,
      } as const;
    }
    return null;
  };

  const openMeasurementDialog = (
    material: ProductionItem,
    source?: { unitType?: 'primary' | 'secondary'; matchedSecondaryKey?: string }
  ) => {
    const pricing = getMaterialPurchasePricing(material);
    const isSized = (material as any).isSized === true;
    const mode: 'weight' | 'volume' = isSized ? 'volume' : 'weight';

    setPendingMeasurementMode(mode);
    setPendingWeightMaterial(material);
    setWeightInput('');

    if (mode === 'volume') {
      const options = getSecondaryVolumeOptions(material, pricing.primaryPrice);
      setPendingVolumeOptions(options);

      const preferredKey = source?.unitType === 'secondary'
        ? (source?.matchedSecondaryKey || options[0]?.key || '')
        : (options[0]?.key || '');
      setSelectedVolumeOptionKey(preferredKey);

      const selected = options.find((option) => option.key === preferredKey) || options[0];
      const selectedPrice = Number(selected?.price ?? pricing.secondaryPrice ?? pricing.primaryPrice);
      const selectedLabel = String(selected?.label || '').trim();
      setPendingWeightUnitPrice(selectedPrice);
      setPendingWeightDescription(selectedLabel ? `${material.name} - ${selectedLabel}` : material.name);
    } else {
      setPendingVolumeOptions([]);
      setSelectedVolumeOptionKey('');
      setPendingWeightUnitPrice(typeof pricing.secondaryPrice === 'number' ? pricing.secondaryPrice : pricing.primaryPrice);
      setPendingWeightDescription(material.name);
    }

    setShowWeightDialog(true);
  };

  const addOrIncrementItem = (materialId: string, unitPrice: number, quantity: number, warehouseId?: string, shelfId?: string) => {
    const headerWarehouseId = isWarehouseEnabled ? (watchedWarehouseId || defaultWarehouseId) : '';
    const targetWarehouseId = isWarehouseEnabled ? (warehouseId ?? headerWarehouseId) : '';
    const targetShelfId = isWarehouseEnabled ? (shelfId ?? defaultShelfId) : '';

    const existingItemIndex = gridItems.findIndex((item) => {
      const sameMaterial = item.materialId === materialId;
      const samePrice = Number(item.unitPrice) === Number(unitPrice);
      if (!isWarehouseEnabled) return sameMaterial && samePrice;
      return sameMaterial && samePrice && (item.warehouseId || '') === targetWarehouseId && (item.shelfId || '') === targetShelfId;
    });

    if (existingItemIndex >= 0) {
      const updatedItems = [...gridItems];
      updatedItems[existingItemIndex].quantity = (updatedItems[existingItemIndex].quantity || 0) + quantity;
      setGridItems(updatedItems);
      return { updatedQuantity: updatedItems[existingItemIndex].quantity, index: existingItemIndex, isNew: false };
    }

    const newIndex = gridItems.length;
    appendGridItem({
      materialId,
      quantity,
      unitPrice,
      lineDiscountPercent: 0,
      lineDiscountAmount: 0,
      bonus: 0,
      warehouseId: targetWarehouseId,
      shelfId: targetShelfId,
      realEstateProjectId: watchedRealEstateProjectId || '',
      realEstateProjectName: selectedRealEstateProject?.name || '',
      realEstateScope: watchedRealEstateLinkMode === 'line-items' ? 'project' : undefined,
      realEstateFloorLabel: '',
      realEstatePartLabel: '',
      realEstateAllocationMethod: watchedRealEstateLinkMode === 'line-items' ? watchedRealEstateAllocationMethod : undefined,
    });
    return { updatedQuantity: quantity, index: newIndex, isNew: true };
  };

  const appendEmptyRow = () => {
    appendGridItem({
      materialId: '',
      quantity: 1,
      unitPrice: 0,
      lineDiscountPercent: 0,
      lineDiscountAmount: 0,
      bonus: 0,
      warehouseId: isWarehouseEnabled ? (watchedWarehouseId || defaultWarehouseId) : '',
      shelfId: isWarehouseEnabled ? defaultShelfId : '',
      realEstateProjectId: watchedRealEstateProjectId || '',
      realEstateProjectName: selectedRealEstateProject?.name || '',
      realEstateScope: watchedRealEstateLinkMode === 'line-items' ? 'project' : undefined,
      realEstateFloorLabel: '',
      realEstatePartLabel: '',
      realEstateAllocationMethod: watchedRealEstateLinkMode === 'line-items' ? 'area' : undefined,
    });
  };

  const handleBarcodeScanned = (barcode: string) => {
    const resolved = resolveMaterialByBarcode(barcode);
    if (!resolved) {
      setAddMaterialInitialValues({ barcode });
      setShowAddMaterialDialog(true);
      setBarcodeInput("");
      return;
    }

    if (resolved.material.isWeighed || (resolved.material as any).isSized) {
      openMeasurementDialog(resolved.material, {
        unitType: resolved.unitType,
        matchedSecondaryKey: resolved.matchedSecondaryKey,
      });
      setBarcodeInput("");
      return;
    }

    const { updatedQuantity, index } = addOrIncrementItem(resolved.material.id, resolved.unitPrice, 1);
    toast({
      title: t?.itemQuantityIncreased ?? 'تمت إضافة الكمية',
      description: `${resolved.material.name}: ${updatedQuantity}`,
    });

    setTimeout(() => focusCell(index, editableColumns.price), 80);

    setBarcodeInput("");
  };

  const handleAddMaterialFromPicker = (material: ProductionItem) => {
    const unitPrice = getPreferredPurchasePrice(material, watchedCurrencyCode || defaultBaseCurrencyCode);

    if (material.isWeighed === true || (material as any).isSized === true) {
      openMeasurementDialog(material, { unitType: 'primary' });
      return;
    }

    if (pickerTargetRowIndex !== null) {
      // Update existing row's material
      const newItems = [...gridItems];
      newItems[pickerTargetRowIndex].materialId = material.id;
      newItems[pickerTargetRowIndex].unitPrice = unitPrice;
      if (isWarehouseEnabled) {
        const effectiveWarehouseId = headerWarehouseId || newItems[pickerTargetRowIndex].warehouseId || existingOrder?.warehouseId || '';
        const candidateShelves = getPrioritizedShelves(material.id, effectiveWarehouseId);
        const currentShelfId = String(newItems[pickerTargetRowIndex].shelfId || '');
        const shelfStillValid = candidateShelves.some((shelf) => shelf.id === currentShelfId);
        if (!shelfStillValid) {
          newItems[pickerTargetRowIndex].shelfId = candidateShelves[0]?.id || '';
        }
      }
      setGridItems(newItems);
      const targetRow = pickerTargetRowIndex;
      setTimeout(() => focusCell(targetRow, editableColumns.price), 80);
    } else {
      const result = addOrIncrementItem(material.id, unitPrice, 1);
      setTimeout(() => focusCell(result.index, editableColumns.price), 80);
    }
  };

  const handleMaterialCreated = (material: ProductionItem) => {
    setExtraMaterials((prev) => {
      if (prev.find((m) => m.id === material.id) || allMaterials.find((m) => m.id === material.id)) {
        return prev;
      }
      return [material, ...prev];
    });

    const unitPrice = getPreferredPurchasePrice(material, watchedCurrencyCode || defaultBaseCurrencyCode);

    if (material.isWeighed === true || (material as any).isSized === true) {
      openMeasurementDialog(material, { unitType: 'primary' });
    } else {
      const result = addOrIncrementItem(material.id, unitPrice, 1);
      setTimeout(() => focusCell(result.index, editableColumns.price), 80);
    }

    setShowAddMaterialDialog(false);
    setAddMaterialInitialValues(undefined);
  };

  const validateWarehouseSelections = (data: z.infer<typeof purchaseOrderSchema>): boolean => {
    if (!isWarehouseEnabled) {
      return true;
    }

    const selectedHeaderWarehouseId = String(data.warehouseId || '').trim();
    if (!selectedHeaderWarehouseId) {
      toast({
        title: tGlobal?.error || 'بيانات ناقصة',
        description: t?.selectWarehouseFirst ?? 'يرجى اختيار المستودع على مستوى الفاتورة قبل الحفظ.',
        variant: 'destructive',
      });
      form.setFocus('warehouseId');
      return false;
    }

    const activeItems = (data.items || []).filter((item) => !isEffectivelyEmptyPurchaseItem(item));
    const missingShelfIndex = activeItems.findIndex((item) => !String(item.shelfId || '').trim());
    if (missingShelfIndex !== -1) {
      toast({
        title: tGlobal?.error || 'بيانات ناقصة',
        description: `${t?.lineLabel ?? 'السطر'} ${missingShelfIndex + 1}: ${t?.selectShelfFirst ?? 'يرجى اختيار الرف قبل حفظ الفاتورة.'}`,
        variant: 'destructive',
      });
      return false;
    }

    const shelfIds = new Set((shelvesByWarehouse.get(selectedHeaderWarehouseId) ?? []).map((shelf) => shelf.id));
    const invalidShelfItem = activeItems.find((item) => {
      const shelfId = String(item.shelfId || '').trim();
      return shelfId && !shelfIds.has(shelfId);
    });
    if (invalidShelfItem) {
      toast({
        title: tGlobal?.error,
        description: t?.invalidShelfForWarehouse ?? 'الرف المحدد لا ينتمي للمستودع المختار.',
        variant: 'destructive',
      });
      return false;
    }

    return true;
  };

  const submitOrder = (
    data: z.infer<typeof purchaseOrderSchema>,
    allowDuplicateOverride = false,
    postingTypeOverride?: 'draft' | 'saved' | 'posted',
    transferCreationModeOverride?: PurchaseTransferCreationMode
  ) => {
    const now = Date.now();
    if (now - submitAttemptCooldownRef.current < 1200) {
      if (process.env.NODE_ENV !== 'production') {
        console.info('[Purchases] Submit throttled', {
          origin: submitOriginRef.current || 'unknown',
          timestamp: new Date().toISOString(),
        });
      }
      return;
    }
    submitAttemptCooldownRef.current = now;

    if (!selectedPartyInfo) {
      toast({
        title: tGlobal?.error,
        description: t?.selectSupplier,
        variant: 'destructive',
      });
      return;
    }

    if (!validateWarehouseSelections(data)) {
      return;
    }

    const effectivePostingType = postingTypeOverride ?? postingType;
    const effectiveTransferCreationMode: PurchaseTransferCreationMode =
      effectivePostingType === 'posted' && documentType === 'tax_invoice' && purchasePostingFollowupEnabled
        ? (transferCreationModeOverride ?? purchaseTransferCreationMode)
        : 'none';
    const submitOrigin = submitOriginRef.current || 'unknown';
    const duplicate = findDuplicateInvoice(selectedPartyInfo.id, data.supplierInvoiceNumber);
    if (duplicate && !allowDuplicateOverride && !data.allowDuplicateInvoice) {
      setDuplicateInfo(duplicate);
      setPendingSubmit(data);
      setPendingPostingType(effectivePostingType);
      setPendingTransferCreationMode(effectiveTransferCreationMode);
      setDuplicateDialogOpen(true);
      return;
    }

    const headerWarehouseId = isWarehouseEnabled ? String(data.warehouseId || '').trim() : '';
    const effectiveRealEstateLinkMode = isRealEstateEnabled ? data.realEstateLinkMode : 'none';

    if (effectiveRealEstateLinkMode === 'line-items') {
      const normalizedProjectId = String(data.realEstateProjectId || '').trim();
      if (!normalizedProjectId) {
        focusRealEstateProjectHeaderField();
        toast({
          title: tGlobal?.error || 'بيانات ناقصة',
          description: t?.lineItemProjectRequired ?? 'في وضع السطور المتعددة يجب تحديد المشروع العقاري أولًا.',
          variant: 'destructive',
        });
        return;
      }

      const lineTargetingIssues: string[] = [];
      (data.items || []).forEach((item, index) => {
        const rowNumber = index + 1;
        const scope = (item.realEstateScope || 'project') as 'project' | 'floor' | 'part';
        const floorLabel = String(item.realEstateFloorLabel || '').trim();
        const partLabel = String(item.realEstatePartLabel || '').trim();
        const allocationMethod = String(item.realEstateAllocationMethod || data.realEstateAllocationMethod || '').trim();

        if (scope === 'floor' && !floorLabel) {
          lineTargetingIssues.push(`${t?.lineLabel ?? 'السطر'} ${rowNumber}: ${t?.realEstateFloorRequired ?? 'الطابق مطلوب عند اختيار نطاق طابق محدد.'}`);
          return;
        }

        if (scope === 'part' && (!floorLabel || !partLabel)) {
          lineTargetingIssues.push(`${t?.lineLabel ?? 'السطر'} ${rowNumber}: ${t?.realEstatePartRequired ?? 'يجب تحديد الطابق والجزء عند اختيار جزء من طابق.'}`);
          return;
        }

        if (scope === 'project' && !allocationMethod) {
          lineTargetingIssues.push(`${t?.lineLabel ?? 'السطر'} ${rowNumber}: ${t?.allocationMethodRequired ?? 'أساس التوزيع مطلوب عند اختيار المبنى كاملًا.'}`);
        }
      });

      if (lineTargetingIssues.length > 0) {
        focusFirstIncompleteLineItemTarget();
        const preview = lineTargetingIssues.slice(0, 3).join(' | ');
        const suffix = lineTargetingIssues.length > 3
          ? ` (+${lineTargetingIssues.length - 3})`
          : '';

        toast({
          title: tGlobal?.error || 'بيانات الربط غير مكتملة',
          description: `${preview}${suffix}`,
          variant: 'destructive',
        });
        return;
      }
    }

    if (data.paymentMethods && data.paymentMethods.length > 0) {
      // Validate that total payment methods equals amount paid
      const totalPaymentAmount = data.paymentMethods.reduce((sum, m) => sum + (Number(m.amount) || 0), 0);
      const epsilon = 0.01;
      if (Math.abs(totalPaymentAmount - Number(data.amountPaid || 0)) > epsilon) {
        toast({
          title: tGlobal?.error,
          description: t?.paymentMethodsAmountMismatch ?? 'مجموع طرق الدفع يجب أن يساوي المبلغ المدفوع.',
          variant: 'destructive',
        });
        return;
      }

      // Validate incoming checks for each payment method
      for (const method of data.paymentMethods) {
        if (method.method === 'check' && method.checkSource === 'incoming' && Number(method.amount || 0) > 0) {
          const selectedIds = Array.isArray(method.incomingCheckIds) ? method.incomingCheckIds : [];
          if (selectedIds.length === 0) {
            toast({
              title: tGlobal?.error,
              description: t?.incomingCheckRequired ?? 'يجب اختيار شيك وارد واحد على الأقل.',
              variant: 'destructive',
            });
            return;
          }

          const selectedChecks = availableIncomingChecks.filter((entry) => selectedIds.includes(entry.id));
          if (selectedChecks.length !== selectedIds.length) {
            toast({
              title: tGlobal?.error,
              description: t?.incomingCheckUnavailable ?? 'بعض الشيكات المختارة غير متاحة الآن.',
              variant: 'destructive',
            });
            return;
          }

          const totalIncomingInOrderCurrency = selectedChecks.reduce((sum, entry) => {
            const amount = Number(entry.amount || 0);
            const fromCurrency = entry.currency || defaultBaseCurrencyCode;
            const toCurrency = watchedCurrencyCode || defaultBaseCurrencyCode;
            return sum + convertAmountByRates(amount, fromCurrency, toCurrency);
          }, 0);

          if (Math.abs(totalIncomingInOrderCurrency - Number(method.amount || 0)) > 0.01) {
            toast({
              title: tGlobal?.error,
              description: t?.incomingCheckAmountMismatch ?? 'مجموع الشيكات الواردة (بعد التحويل) يجب أن يساوي مبلغ طريقة الدفع.',
              variant: 'destructive',
            });
            return;
          }
        }
      }
    }

    const showKnownErrorToast = (code?: string) => {
      if ((code === 'INSUFFICIENT_STOCK_FOR_REVERSE' || code === 'INVENTORY_RECONCILE_FAILED') && mode !== 'edit') {
        return false;
      }

      const entries: Record<string, { title: string; description: string }> = {
        PERIOD_LOCKED: {
          title: t?.periodLocked || tGlobal?.error || 'الفترة مقفلة',
          description: t?.periodLockedDesc || 'لا يمكن التعديل داخل فترة مقفلة. عدّل التاريخ أو افتح الفترة.',
        },
        INVENTORY_LOCKED: {
          title: t?.inventoryLocked || tGlobal?.error || 'جرد مقفل',
          description: t?.inventoryLockedDesc || 'لا يمكن التعديل بسبب إقفال الجرد. افتح الجرد أو استخدم تاريخ أحدث.',
        },
        INSUFFICIENT_STOCK_FOR_REVERSE: {
          title: t?.insufficientStock || tGlobal?.error || 'المخزون غير كافٍ',
          description: t?.insufficientStockReverse || 'لا يوجد مخزون كافٍ لعكس الكمية المخفضة. تحقق من الكميات أو أنشئ إرجاع/جرد.',
        },
        INVENTORY_RECONCILE_FAILED: {
          title: tGlobal?.error || 'فشل التسوية',
          description: t?.inventoryReconcileFailed || 'فشلت تسوية المخزون. تحقق من الكميات أو الأقفال ثم أعد المحاولة.',
        },
        POSTED_ORDER_MODE_LOCKED: {
          title: t?.postedOrderModeLockedTitle || tGlobal?.error || 'الفاتورة مرحلة',
          description: t?.postedOrderModeLockedDesc || 'لا يمكن تغيير حالة الفاتورة المرحلة إلى غير مرحلة.',
        },
        POSTED_ORDER_EDIT_LOCKED: {
          title: t?.postedOrderEditLockedTitle || tGlobal?.error || 'الفاتورة مرحلة',
          description: t?.postedOrderEditLockedDesc || 'لا يمكن تعديل الفاتورة بعد الترحيل. استخدم إجراء عكسي أو تسوية.',
        },
        PURCHASE_ORDER_LOCKED: {
          title: t?.purchaseOrderLocked || tGlobal?.error || 'الفاتورة قيد التعديل',
          description: t?.purchaseOrderLockedDesc || 'لا يمكن حفظ التعديل لأن مستخدمًا آخر يقوم بتعديل الفاتورة حاليًا.',
        },
        INVALID_PURCHASE_ACTION_SIGNATURE: {
          title: tGlobal?.error || 'طلب غير صالح',
          description: t?.invalidPurchaseActionSignature ?? 'انتهت صلاحية جلسة الحفظ أو أن الطلب غير موثوق. أعد تحميل الصفحة ثم حاول مرة أخرى.',
        },
      };

      const entry = code ? entries[code] : undefined;
      if (!entry) return false;
      toast({ title: entry.title, description: entry.description, variant: 'destructive' });
      return true;
    };

    startTransition(async () => {
      if (process.env.NODE_ENV !== 'production') {
        console.info('[Purchases] Submit attempt', {
          origin: submitOrigin,
          mode,
          postingType: effectivePostingType,
          itemCount: Array.isArray(data.items) ? data.items.length : 0,
          supplierId: selectedPartyInfo.id,
          timestamp: new Date().toISOString(),
        });
      }
      submitOriginRef.current = 'unknown';
      try {
        const baseCode = watchedBaseCurrencyCode || defaultBaseCurrencyCode;
        const currencyCode = watchedCurrencyCode || defaultBaseCurrencyCode;
        const lockedEditRate = mode === 'edit' && existingOrder
          ? Number(existingOrder.exchangeRate || 1)
          : null;
        const effectiveRateForPayload = lockedEditRate !== null
          ? lockedEditRate
          : (currencyCode === baseCode ? 1 : effectiveExchangeRate);
        const grandTotalBase = grandTotal * effectiveRateForPayload;
        const amountPaidBase = data.amountPaid * effectiveRateForPayload;
        const amountDueBaseVal = amountDue * effectiveRateForPayload;

        const selectedProjectName = String(selectedRealEstateProject?.name || data.realEstateProjectName || '').trim();
        const payload = {
          __submitOrigin: submitOrigin,
          __purchaseActionGuard: actionGuardToken,
          supplierId: selectedPartyInfo.id,
          supplierName: selectedPartyInfo.name,
          supplierInvoiceNumber: data.supplierInvoiceNumber,
          supplierInvoiceDate: data.supplierInvoiceDate,
          notes: String(data.notes || '').trim() || undefined,
          warehouseId: headerWarehouseId,
          realEstateLinkMode: effectiveRealEstateLinkMode || 'none',
          realEstateProjectId: isRealEstateEnabled ? (String(data.realEstateProjectId || '').trim() || undefined) : undefined,
          realEstateProjectName: isRealEstateEnabled ? (selectedProjectName || undefined) : undefined,
          realEstateScope: isRealEstateEnabled ? (data.realEstateScope || 'project') : undefined,
          realEstateFloorLabel: isRealEstateEnabled ? (String(data.realEstateFloorLabel || '').trim() || undefined) : undefined,
          realEstatePartLabel: isRealEstateEnabled ? (String(data.realEstatePartLabel || '').trim() || undefined) : undefined,
          realEstateAllocationMethod: isRealEstateEnabled
            ? ((data.realEstateAllocationMethod || selectedRealEstateProject?.sharedCostAllocationMethod || 'area') as 'area' | 'sale-value' | 'manual-share')
            : undefined,
          allowDuplicateInvoice: allowDuplicateOverride || data.allowDuplicateInvoice,
          currencyCode,
          baseCurrencyCode: baseCode,
          exchangeRate: effectiveRateForPayload,
          rateDate: form.getValues('rateDate') || defaultRateDate,
          rateSource: watchedRateSource,
          isAutoRate: watchedIsAutoRate,
          items: itemsWithDetails.map(item => ({
            materialId: item.materialId,
            name: item.name,
            quantity: item.quantity,
            unitPrice: item.unitPrice,
            total: item.total,
            lineDiscountPercent: item.lineDiscountPercent ?? 0,
            lineDiscountAmount: item.lineDiscountAmount ?? 0,
            bonus: item.bonus ?? 0,
            warehouseId: headerWarehouseId,
            shelfId: item.shelfId,
            taxRate: item.taxRate,
            realEstateProjectId: isRealEstateEnabled ? (String(item.realEstateProjectId || data.realEstateProjectId || '').trim() || undefined) : undefined,
            realEstateProjectName: isRealEstateEnabled ? (String(item.realEstateProjectName || selectedProjectName || '').trim() || undefined) : undefined,
            realEstateScope: isRealEstateEnabled ? ((effectiveRealEstateLinkMode === 'line-items' ? item.realEstateScope : data.realEstateScope) || undefined) : undefined,
            realEstateFloorLabel: isRealEstateEnabled ? (String(effectiveRealEstateLinkMode === 'line-items' ? item.realEstateFloorLabel : data.realEstateFloorLabel || '').trim() || undefined) : undefined,
            realEstatePartLabel: isRealEstateEnabled ? (String(effectiveRealEstateLinkMode === 'line-items' ? item.realEstatePartLabel : data.realEstatePartLabel || '').trim() || undefined) : undefined,
            realEstateAllocationMethod: isRealEstateEnabled && ((effectiveRealEstateLinkMode === 'line-items' ? item.realEstateScope : data.realEstateScope) === 'project')
              ? ((item.realEstateAllocationMethod || data.realEstateAllocationMethod || selectedRealEstateProject?.sharedCostAllocationMethod || 'area') as 'area' | 'sale-value' | 'manual-share')
              : undefined,
          })),
          subTotal,
          taxMethod: data.taxMethod || 'tax-inclusive',
          postingType: effectivePostingType,
          purchaseTransferCreationMode:
            effectivePostingType === 'posted' && documentType === 'tax_invoice'
              ? effectiveTransferCreationMode
              : undefined,
          invoiceTaxRate: data.invoiceTaxRate || 0,
          invoiceDiscountPercent: data.invoiceDiscountPercent || 0,
          invoiceDiscountAmount: data.invoiceDiscountAmount || 0,
          taxAmount,
          grandTotal,
          amountPaid: data.amountPaid,
          paymentMethods: (data.paymentMethods || []).map((method) => ({
            ...method,
            currencyCode: (method as { currency?: string }).currency || currencyCode,
          })),
          amountDue,
          grandTotalBase,
          amountPaidBase,
          amountDueBase: amountDueBaseVal,
          documents: orderDocuments,
          documentType: shipmentWorkflowEnabled ? documentType : 'tax_invoice',
          linkedShipmentIds: shipmentWorkflowEnabled && documentType === 'tax_invoice' ? linkedShipmentIds : [],
        };

        const result = mode === 'edit' && existingOrder
          ? await handleUpdatePurchaseOrder({ id: existingOrder.id, ...payload })
          : await handleCreatePurchaseOrder(payload);

        if (!('error' in result) || !result.error) {
          if (mode === 'edit' && existingOrder?.id && editLockOwnedRef.current) {
            await handleReleasePurchaseOrderLock(existingOrder.id);
            editLockOwnedRef.current = false;
          }

          toast({
            title: mode === 'edit' ? t?.saveOrderSuccess ?? 'تم التحديث' : t?.saveOrderSuccess,
            description: `${t?.orderNumber}: ${(result as any).orderNumber || existingOrder?.orderNumber}`,
          });
          if (mode === 'edit') {
            router.push('/admin/purchases/history');
            return;
          }
          if (mode === 'create') {
            setStockReport(null);
            setShowStockReportDialog(false);
            setGridItems([]);
            setPaymentMethods([]);
            setOrderDocuments([]);
            setBarcodeInput('');
            form.reset();
            setSelectedPartyId('');
            setDuplicateInfo(null);
            setPendingSubmit(null);
            setSupplierInvoiceDuplicateInfo(null);
          }
        } else if (result.error === 'DUPLICATE_SUPPLIER_INVOICE') {
          setDuplicateInfo({
            id: 'dup',
            orderNumber: ('existing' in result ? result.existing?.orderNumber : undefined) || '-',
            date: ('existing' in result ? result.existing?.date : undefined) || '',
            supplierId: selectedPartyInfo.id,
            supplierName: selectedPartyInfo.name,
            items: [],
            subTotal: 0,
            taxMethod: data.taxMethod || 'invoice-level',
            taxAmount: 0,
            grandTotal: ('existing' in result ? result.existing?.grandTotal : undefined) || 0,
            amountPaid: 0,
            amountDue: ('existing' in result ? result.existing?.amountDue : undefined) || 0,
            status: 'active',
            createdBy: '',
            createdAt: '',
            supplierInvoiceNumber: data.supplierInvoiceNumber,
          } as PurchaseOrder);
          setPendingSubmit(data);
          setPendingPostingType(effectivePostingType);
          setPendingTransferCreationMode(effectiveTransferCreationMode);
          setDuplicateDialogOpen(true);
        } else {
          if (result.error === 'PURCHASE_ORDER_LOCKED') {
            const lockedByName = 'lockedBy' in result ? (result.lockedBy || 'مستخدم آخر') : 'مستخدم آخر';
            toast({
              title: t?.purchaseOrderLocked || tGlobal?.error || 'الفاتورة قيد التعديل',
              description: (t?.purchaseOrderLockedBy || 'يتم التعديل على الفاتورة من قبل {name}.').replace('{name}', lockedByName),
              variant: 'destructive',
            });
            return;
          }

          if (!showKnownErrorToast(result.error)) {
            const validationErrorMessage =
              (result as any)?.validationSummary
              ||
              (Array.isArray((result as any)?.formErrors) && (result as any).formErrors[0])
              || (result as any)?.validationErrors && Object.values((result as any).validationErrors).flat().find(Boolean)
              || undefined;
            toast({
              title: tGlobal?.error,
              description: validationErrorMessage || result.error || t?.saveOrderError,
              variant: 'destructive',
            });
          }
        }
      } catch (error) {
        if (!showKnownErrorToast((error as any)?.message)) {
          toast({
            title: tGlobal?.error,
            description: t?.saveOrderError,
            variant: 'destructive',
          });
        }
      }
    });
  };

  const onSubmit = (data: z.infer<typeof purchaseOrderSchema>) => {
    if (submitOriginRef.current === 'unknown') {
      submitOriginRef.current = 'form-submit';
    }
    if (!validateWarehouseSelections(data)) {
      return;
    }
    setPendingPostingSubmit(data);
    setPostingDialogOpen(true);
  };

  const getFirstErrorMessage = (errors: any): string | null => {
    if (!errors) return null;
    if (errors?.message) return String(errors.message);
    if (typeof errors === 'object') {
      for (const key of Object.keys(errors)) {
        const nested = getFirstErrorMessage(errors[key]);
        if (nested) return nested;
      }
    }
    return null;
  };

  const onInvalidSubmit = (errors: any) => {
    const firstError = getFirstErrorMessage(errors);
    toast({
      title: tGlobal?.error || 'خطأ في التحقق',
      description: firstError || t?.saveOrderValidationError || 'يرجى تعبئة الحقول الإلزامية قبل الحفظ.',
      variant: 'destructive',
    });
  };

  const isBaseCurrency = watchedCurrencyCode === defaultBaseCurrencyCode;
  const isFxLocked = mode === 'edit' && !!existingOrder;
  const headerWarehouseId = isWarehouseEnabled ? (watchedWarehouseId || defaultWarehouseId || '') : '';
  const headerShelves = isWarehouseEnabled ? (shelvesByWarehouse.get(headerWarehouseId) ?? []) : [];
  const numericNoSpinClass = 'appearance-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none';
  const hasRealEstateLineColumn = isRealEstateEnabled && watchedRealEstateLinkMode === 'line-items';
  const gridColSpan = editableColumns.count + 2 + (hasRealEstateLineColumn ? 1 : 0);

  const lineItemTargetingSummary = useMemo(() => {
    if (!hasRealEstateLineColumn) {
      return null;
    }

    let projectCount = 0;
    let floorCount = 0;
    let partCount = 0;
    const issues: string[] = [];

    gridItems.forEach((item, index) => {
      const scope = (item.realEstateScope || 'project') as 'project' | 'floor' | 'part';
      const floorLabel = String(item.realEstateFloorLabel || '').trim();
      const partLabel = String(item.realEstatePartLabel || '').trim();
      const allocationMethod = String(item.realEstateAllocationMethod || watchedRealEstateAllocationMethod || '').trim();
      const rowNumber = index + 1;

      if (scope === 'project') {
        projectCount += 1;
        if (!allocationMethod) {
          issues.push(`${t?.lineLabel ?? 'السطر'} ${rowNumber}: ${t?.allocationMethodRequired ?? 'أساس التوزيع مطلوب.'}`);
        }
        return;
      }

      if (scope === 'floor') {
        floorCount += 1;
        if (!floorLabel) {
          issues.push(`${t?.lineLabel ?? 'السطر'} ${rowNumber}: ${t?.realEstateFloorRequired ?? 'الطابق مطلوب.'}`);
        }
        return;
      }

      partCount += 1;
      if (!floorLabel || !partLabel) {
        issues.push(`${t?.lineLabel ?? 'السطر'} ${rowNumber}: ${t?.realEstatePartRequired ?? 'الطابق والجزء مطلوبان.'}`);
      }
    });

    if (!String(watchedRealEstateProjectId || '').trim()) {
      issues.unshift(t?.lineItemProjectRequired ?? 'في وضع السطور المتعددة يجب تحديد المشروع العقاري أولًا.');
    }

    return {
      total: gridItems.length,
      projectCount,
      floorCount,
      partCount,
      issues,
    };
  }, [
    hasRealEstateLineColumn,
    gridItems,
    watchedRealEstateAllocationMethod,
    watchedRealEstateProjectId,
    t,
  ]);

  const lineItemTargetingIssuesByRow = useMemo(() => {
    if (!hasRealEstateLineColumn) {
      return new Map<number, { scope?: boolean; floor?: boolean; part?: boolean; allocation?: boolean }>();
    }

    const issuesByRow = new Map<number, { scope?: boolean; floor?: boolean; part?: boolean; allocation?: boolean }>();
    gridItems.forEach((item, index) => {
      const scope = (item.realEstateScope || 'project') as 'project' | 'floor' | 'part';
      const floorLabel = String(item.realEstateFloorLabel || '').trim();
      const partLabel = String(item.realEstatePartLabel || '').trim();
      const allocationMethod = String(item.realEstateAllocationMethod || watchedRealEstateAllocationMethod || '').trim();

      if (scope === 'project' && !allocationMethod) {
        issuesByRow.set(index, { ...(issuesByRow.get(index) || {}), scope: true, allocation: true });
      }

      if (scope === 'floor' && !floorLabel) {
        issuesByRow.set(index, { ...(issuesByRow.get(index) || {}), scope: true, floor: true });
      }

      if (scope === 'part') {
        const nextIssues = { ...(issuesByRow.get(index) || {}), scope: true };
        if (!floorLabel) {
          nextIssues.floor = true;
        }
        if (!partLabel) {
          nextIssues.part = true;
        }
        if (nextIssues.floor || nextIssues.part) {
          issuesByRow.set(index, nextIssues);
        }
      }
    });

    return issuesByRow;
  }, [hasRealEstateLineColumn, gridItems, watchedRealEstateAllocationMethod]);

  const focusFirstIncompleteLineItemTarget = useCallback(() => {
    if (!hasRealEstateLineColumn) {
      return;
    }

    const firstIssueEntry = Array.from(lineItemTargetingIssuesByRow.entries()).sort((left, right) => left[0] - right[0])[0];
    if (!firstIssueEntry) {
      return;
    }

    const [rowIndex, issue] = firstIssueEntry;
    const rowSelector = `[data-real-estate-row="${rowIndex}"]`;
    const targetElement = issue.part
      ? document.querySelector<HTMLElement>(`${rowSelector} [data-real-estate-field="part"]`)
      : issue.floor
        ? document.querySelector<HTMLElement>(`${rowSelector} [data-real-estate-field="floor"]`)
        : document.querySelector<HTMLElement>(`${rowSelector} [data-real-estate-field="scope"]`);

    setActiveGridRowIndex(rowIndex);

    if (targetElement) {
      targetElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
      requestAnimationFrame(() => targetElement.focus());
      return;
    }

    requestAnimationFrame(() => focusCell(rowIndex, 0));
  }, [hasRealEstateLineColumn, lineItemTargetingIssuesByRow]);

  const focusRealEstateProjectHeaderField = useCallback(() => {
    const targetElement = document.querySelector<HTMLElement>('[data-real-estate-header-field="project"]');
    if (!targetElement) {
      return;
    }

    targetElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
    requestAnimationFrame(() => targetElement.focus());
  }, []);

  const buildPurchasePriceReviewRows = (): PurchasePriceReviewRow[] => {
    const currentCurrency = watchedCurrencyCode || defaultBaseCurrencyCode;
    return itemsWithDetails
      .map((item) => {
        // Find the latest comparable history entry for this material
        const historyEntry = purchasePriceHistoryRows.find(
          (entry) => entry.materialId === item.materialId && !(existingOrder?.id && entry.orderId === existingOrder.id)
        );
        if (!historyEntry) return null;

        const previousOriginalPrice = Number(historyEntry.adjustedUnitPrice || 0);
        if (!Number.isFinite(previousOriginalPrice) || previousOriginalPrice <= 0) return null;

        // Convert the historical price to the current invoice currency for fair comparison
        const previousPrice = historyEntry.currencyCode === currentCurrency
          ? previousOriginalPrice
          : convertAmountByRates(previousOriginalPrice, historyEntry.currencyCode, currentCurrency);

        const newPrice = Number(item.unitPrice || 0);
        if (!Number.isFinite(newPrice) || newPrice <= 0) return null;
        if (!Number.isFinite(previousPrice) || previousPrice <= 0) return null;

        const difference = Number((newPrice - previousPrice).toFixed(2));
        if (Math.abs(difference) < 0.0001) return null;

        return {
          materialId: item.materialId,
          materialName: item.name,
          previousPrice,
          previousOriginalPrice,
          previousCurrencyCode: historyEntry.currencyCode,
          newPrice,
          difference,
          changeType: difference > 0 ? 'increase' : 'decrease',
        };
      })
      .filter((entry): entry is PurchasePriceReviewRow => entry !== null)
      .sort((left, right) => Math.abs(right.difference) - Math.abs(left.difference));
  };

  const submitWithPurchasePriceReview = (
    data: z.infer<typeof purchaseOrderSchema>,
    allowDuplicateOverride = false,
    postingTypeOverride?: 'draft' | 'saved' | 'posted',
    transferCreationModeOverride?: PurchaseTransferCreationMode
  ) => {
    const reviewRows = buildPurchasePriceReviewRows();
    if (reviewRows.length === 0) {
      submitOrder(data, allowDuplicateOverride, postingTypeOverride, transferCreationModeOverride);
      return;
    }

    const effectivePostingType = postingTypeOverride ?? postingType;
    const effectiveTransferCreationMode: PurchaseTransferCreationMode =
      effectivePostingType === 'posted' && documentType === 'tax_invoice' && purchasePostingFollowupEnabled
        ? (transferCreationModeOverride ?? purchaseTransferCreationMode)
        : 'none';

    setPriceReviewRows(reviewRows);
    setPendingPriceReviewSubmission({
      data,
      allowDuplicateOverride,
      postingType: effectivePostingType,
      purchaseTransferCreationMode: effectiveTransferCreationMode,
    });
    setPriceReviewDialogOpen(true);
  };

  const handleUnitPriceBlur = (materialId: string, nextPrice: number) => {
    if (!autoUpdateSalePrice) return;
    const materialToUpdate = allMaterials.find((m) => m.id === materialId);
    if (!materialToUpdate) return;
    const currentPurchasePrice = Number(materialToUpdate.purchasePrice || 0);
    const normalizedNext = Number.isFinite(nextPrice) ? nextPrice : 0;
    if (normalizedNext === currentPurchasePrice) return;

    // افتح نافذة تحديث الصنف مع تركيز على سعر البيع ليتناسب مع سعر الشراء الجديد
    setUpdateMaterialItem({ ...materialToUpdate, purchasePrice: normalizedNext });
    setUpdateMaterialDialogOpen(true);
  };

  const handlePickDocuments = () => {
    if (isPending || isUploadingDocument) return;
    documentInputRef.current?.click();
  };

  const handleUploadDocuments = async (files: FileList | null) => {
    if (!files || files.length === 0) return;

    setIsUploadingDocument(true);
    try {
      const uploadedDocs: PurchaseOrderDocument[] = [];
      for (const file of Array.from(files)) {
        const formData = new FormData();
        formData.append('file', file);

        const response = await fetch('/api/admin/purchases/documents', {
          method: 'POST',
          body: formData,
        });

        const result = await response.json();
        if (!response.ok || !result?.document) {
          throw new Error(result?.error || t?.documentUploadFailed || 'فشل رفع الوثيقة');
        }

        uploadedDocs.push(result.document as PurchaseOrderDocument);
      }

      setOrderDocuments((prev) => [...prev, ...uploadedDocs]);
      toast({
        title: tGlobal?.success || 'تم',
        description: (t?.documentsUploadedSuccess || 'تم رفع {count} وثيقة بنجاح').replace('{count}', String(uploadedDocs.length)),
      });
    } catch (error: any) {
      toast({
        title: tGlobal?.error || 'خطأ',
        description: error?.message || t?.documentUploadFailed || 'فشل رفع الوثيقة',
        variant: 'destructive',
      });
    } finally {
      if (documentInputRef.current) {
        documentInputRef.current.value = '';
      }
      setIsUploadingDocument(false);
    }
  };

  const removeDocument = (docId: string) => {
    setOrderDocuments((prev) => prev.filter((doc) => doc.id !== docId));
  };

  const handleAiExtraction = async () => {
    if (!aiInvoiceEntryEnabled) {
      toast({
        title: tGlobal?.error || 'خطأ',
        description: 'ميزة الإدخال الذكي للفواتير غير مفعلة من الإعدادات العامة.',
        variant: 'destructive',
      });
      return;
    }

    setIsAiExtracting(true);
    try {
      const extractionInput: any = {
        language: 'ar', // or detect from browser locale
      };

      if (aiExtractionMode === 'image' && aiExtractionDocument) {
        extractionInput.filePath = aiExtractionDocument.filePath;
      } else if (aiExtractionMode === 'voice' && aiExtractionVoiceText.trim()) {
        extractionInput.transcriptText = aiExtractionVoiceText;
      } else {
        throw new Error('يجب تحديد صورة أو نص صوتي للتحليل');
      }

      const response = await fetch('/api/admin/purchases/ai-extract', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(extractionInput),
      });

      const rawText = await response.text();
      let result: any = null;
      try {
        result = rawText ? JSON.parse(rawText) : null;
      } catch {
        throw new Error('تعذر قراءة استجابة الخادم. تحقق من سجل الخادم (server logs).');
      }
      if (!response.ok) {
        throw new Error(result?.error || 'فشل التحليل الذكي');
      }

      setAiExtractionResult(result.data);
      setAiExtractionConfidence(result.data.confidence || 0);
      setAiExtractionDialogOpen(false);
      setAiReviewDialogOpen(true);

      toast({
        title: 'نجح التحليل',
        description: `تم استخراج ${result.data.items?.length || 0} أصناف من الفاتورة`,
      });
    } catch (error: any) {
      toast({
        title: tGlobal?.error || 'خطأ',
        description: error?.message || 'فشل التحليل الذكي',
        variant: 'destructive',
      });
    } finally {
      setIsAiExtracting(false);
    }
  };

  const handleApplyAiExtraction = async () => {
    if (!aiExtractionResult) return;

    try {
      const result = aiExtractionResult;

      // Update supplier
      const selectedSupplier = supplierList.find((s) => 
        s.name.toLowerCase().includes(result.supplierName.toLowerCase()) ||
        result.supplierName.toLowerCase().includes(s.name.toLowerCase())
      );

      if (selectedSupplier) {
        form.setValue('supplierId', selectedSupplier.id);
        setSelectedPartyId(`supplier:${selectedSupplier.id}`);
      } else {
        // Show suggestion but allow manual override
        toast({
          title: 'تحذير',
          description: `لم يتم العثور على المورد "${result.supplierName}" - يرجى اختيار مورد يدويًا`,
        });
      }

      if (result.invoiceNumber) {
        form.setValue('supplierInvoiceNumber', result.invoiceNumber);
      }
      if (result.invoiceDate) {
        form.setValue('supplierInvoiceDate', result.invoiceDate);
      }

      // Add items
      if (Array.isArray(result.items) && result.items.length > 0) {
        const newItems = await Promise.all(
          result.items.map(async (aiItem: any) => {
            const matchedMaterial = materials.find((m) =>
              m.name.toLowerCase().includes(aiItem.name.toLowerCase()) ||
              aiItem.name.toLowerCase().includes(m.name.toLowerCase())
            );

            return {
              materialId: matchedMaterial?.id || '',
              quantity: Math.max(1, Number(aiItem.quantity) || 1),
              unitPrice: Math.max(0, Number(aiItem.unitPrice) || 0),
              lineDiscountPercent: 0,
              lineDiscountAmount: 0,
              bonus: 0,
              warehouseId: defaultWarehouseId || '',
              shelfId: defaultShelfId || '',
              taxRate: result.taxRate ? Number(result.taxRate) * 100 : 0,
              realEstateProjectId: '',
              realEstateProjectName: '',
              realEstateFloorLabel: '',
              realEstatePartLabel: '',
              realEstateAllocationMethod: 'area' as const,
            };
          })
        );

        setGridItems(newItems);
        form.setValue('items', newItems);
      }

      setAiReviewDialogOpen(false);
      toast({
        title: 'تم تطبيق البيانات',
        description: 'تم ملء نموذج الفاتورة ببيانات التحليل - يرجى المراجعة قبل الحفظ',
      });
    } catch (error: any) {
      toast({
        title: tGlobal?.error || 'خطأ',
        description: error?.message || 'فشل تطبيق البيانات المستخرجة',
        variant: 'destructive',
      });
    }
  };

  if (!mounted) {
    return null;
  }

  return (
    <div className="w-full max-w-[1900px] mx-auto px-3 sm:px-4 lg:px-6 pb-10">
      <AddSupplierDialog
        open={showAddSupplierDialog}
        onOpenChange={setShowAddSupplierDialog}
        t={t}
        onSupplierAdded={(supplier) => {
          setSupplierList((prev) => [...prev, supplier]);
          setSelectedPartyId(`supplier:${supplier.id}`);
          form.setValue('supplierId', supplier.id);
        }}
      />
      <Dialog
        open={showAddMaterialDialog}
        onOpenChange={(open) => {
          if (!open) {
            setAddMaterialInitialValues(undefined);
          }
          setShowAddMaterialDialog(open);
        }}
      >
        <MaterialItemDialog
          items={allMaterials}
          t={t}
          tGlobal={tGlobal}
          itemGroups={itemGroups}
          categories={categories}
          active={showAddMaterialDialog}
          initialValues={addMaterialInitialValues}
          onFinished={() => {
            setShowAddMaterialDialog(false);
            setAddMaterialInitialValues(undefined);
          }}
          onCreated={(item) => handleMaterialCreated(item as ProductionItem)}
        />
      </Dialog>
      <Dialog
        open={updateMaterialDialogOpen}
        onOpenChange={(open) => {
          if (!open) {
            setUpdateMaterialItem(null);
          }
          setUpdateMaterialDialogOpen(open);
        }}
      >
        <MaterialItemDialog
          items={allMaterials}
          t={t}
          tGlobal={tGlobal}
          itemGroups={itemGroups}
          categories={categories}
          active={updateMaterialDialogOpen}
          item={updateMaterialItem || undefined}
          focusSalePrice
          onFinished={() => {
            setUpdateMaterialDialogOpen(false);
            setUpdateMaterialItem(null);
          }}
        />
      </Dialog>
      <Dialog open={duplicateDialogOpen} onOpenChange={setDuplicateDialogOpen}>
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle>{t?.duplicateInvoiceTitle ?? 'فاتورة مكررة'}</DialogTitle>
            <DialogDescription>
              {duplicateInfo
                ? `${t?.duplicateInvoiceMessage ?? 'تم إدخال فاتورة المورد مسبقًا.'}`
                : (t?.duplicateInvoiceMessage ?? 'تم إدخال فاتورة المورد مسبقًا.')}
            </DialogDescription>
          </DialogHeader>
          {duplicateInfo && (
            <div className="space-y-2 rounded-md border bg-muted/20 p-3 text-sm">
              <div>{t?.orderNumber ?? 'رقم الأمر'}: {duplicateInfo.orderNumber || '-'}</div>
              <div>{t?.supplierInvoiceNumber ?? 'رقم فاتورة المورد'}: {duplicateInfo.supplierInvoiceNumber || '-'}</div>
              <div>{t?.orderDate ?? 'تاريخ الأمر'}: {duplicateInfo.date ? format(new Date(duplicateInfo.date), 'PPP') : '-'}</div>
              <div>{t?.total ?? 'الإجمالي'}: {formatCurrency(duplicateInfo.grandTotal || 0, currencySymbol)}</div>
            </div>
          )}
          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setDuplicateDialogOpen(false);
                setPendingSubmit(null);
              }}
            >
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              onClick={() => {
                const data = pendingSubmit;
                setDuplicateDialogOpen(false);
                if (data) {
                  submitOriginRef.current = 'duplicate-dialog-continue';
                  submitWithPurchasePriceReview({
                    ...data,
                    allowDuplicateInvoice: true,
                  }, true, pendingPostingType, pendingTransferCreationMode);
                }
              }}
            >
              {t?.continue ?? 'المتابعة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Dialog
        open={postingDialogOpen}
        onOpenChange={(open) => {
          setPostingDialogOpen(open);
        }}
      >
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle>
              {documentType === 'shipment'
                ? 'اختر حالة حفظ الارسالية'
                : (t?.saveOrderModalTitle ?? 'اختر حالة حفظ الفاتورة')}
            </DialogTitle>
            <DialogDescription>
              {documentType === 'shipment'
                ? 'حدد طريقة حفظ الارسالية قبل المتابعة.'
                : (t?.saveOrderModalDescription ?? 'حدد طريقة حفظ الفاتورة قبل المتابعة.')}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <label className="flex items-start gap-3 rounded-md border p-3 cursor-pointer">
              <input
                type="radio"
                name="posting-type"
                checked={postingType === 'draft'}
                onChange={() => setPostingType('draft')}
                className="mt-1 h-4 w-4"
                disabled={mode === 'edit' && existingOrder?.postingStatus === 'posted'}
              />
              <div>
                <div className="font-medium">{t?.postingDraftLabel ?? 'مسودة'}</div>
                <div className="text-xs text-muted-foreground">
                  {documentType === 'shipment'
                    ? (t?.shipmentPostingDraftDesc ?? 'حفظ الارسالية بدون أي تأثير مخزني أو محاسبي.')
                    : (t?.postingDraftDesc ?? 'حفظ بدون ترحيل أو تأثير مخزني/محاسبي.')}
                </div>
              </div>
            </label>
            <label className="flex items-start gap-3 rounded-md border p-3 cursor-pointer">
              <input
                type="radio"
                name="posting-type"
                checked={postingType === 'saved'}
                onChange={() => setPostingType('saved')}
                className="mt-1 h-4 w-4"
                disabled={mode === 'edit' && existingOrder?.postingStatus === 'posted'}
              />
              <div>
                <div className="font-medium">{t?.postingSavedLabel ?? 'محفوظ'}</div>
                <div className="text-xs text-muted-foreground">
                  {documentType === 'shipment'
                    ? (t?.shipmentPostingSavedDesc ?? 'تأثير مخزني فوري مع إنشاء مسودة قيد محاسبي (GRNI) للمراجعة.')
                    : (t?.postingSavedDesc ?? 'حفظ الفاتورة دون ترحيل نهائي.')}
                </div>
              </div>
            </label>
            {documentType !== 'shipment' && (
              <label className="flex items-start gap-3 rounded-md border p-3 cursor-pointer">
                <input
                  type="radio"
                  name="posting-type"
                  checked={postingType === 'posted'}
                  onChange={() => setPostingType('posted')}
                  className="mt-1 h-4 w-4"
                />
                <div>
                  <div className="font-medium">{t?.postingPostedLabel ?? 'مرحل'}</div>
                  <div className="text-xs text-muted-foreground">
                    {t?.postingPostedDesc ?? 'حفظ وترحيل محاسبي ومخزني مباشر.'}
                  </div>
                </div>
              </label>
            )}
          </div>
          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setPostingDialogOpen(false);
                setPendingPostingSubmit(null);
                setPendingTransferCreationMode(purchaseTransferCreationMode);
              }}
            >
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              disabled={isPending || isAcquiringEditLock || !hasEditLock}
              onClick={() => {
                if (!pendingPostingSubmit) return;
                submitOriginRef.current = 'posting-dialog-confirm';
                if (postingType === 'posted' && documentType === 'tax_invoice' && purchasePostingFollowupEnabled) {
                  setPendingTransferCreationMode(purchaseTransferCreationMode);
                  setPostingDialogOpen(false);
                  setPostingFollowupDialogOpen(true);
                  return;
                }

                setPostingDialogOpen(false);
                submitWithPurchasePriceReview(pendingPostingSubmit, false, postingType, 'none');
                setPendingPostingSubmit(null);
              }}
            >
              {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
              {t?.confirmSaveOrder ?? 'تأكيد الحفظ'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {purchasePostingFollowupEnabled && (
      <Dialog
        open={postingFollowupDialogOpen}
        onOpenChange={(open) => {
          setPostingFollowupDialogOpen(open);
          if (!open) {
            setPendingPostingSubmit(null);
          }
        }}
      >
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle>{t?.purchasePostingFollowupTitle ?? 'الخطوة التالية بعد الترحيل'}</DialogTitle>
            <DialogDescription>{t?.purchasePostingFollowupDescription ?? 'حدد الإجراء المطلوب بعد حفظ وترحيل فاتورة المشتريات.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <label className="flex items-start gap-3 rounded-md border p-3 cursor-pointer">
              <input
                type="radio"
                name="purchase-transfer-creation-mode"
                checked={purchaseTransferCreationMode === 'direct_internal_transfer'}
                onChange={() => setPurchaseTransferCreationMode('direct_internal_transfer')}
                className="mt-1 h-4 w-4"
              />
              <div>
                <div className="font-medium">{t?.purchasePostingFollowupDirectLabel ?? 'إنشاء ارسالية داخلية مباشرة'}</div>
                <div className="text-xs text-muted-foreground">{t?.purchasePostingFollowupDirectDesc ?? 'إنشاء سند ارسالية داخلية مكتمل الاستلام مباشرة.'}</div>
              </div>
            </label>
            <label className="flex items-start gap-3 rounded-md border p-3 cursor-pointer">
              <input
                type="radio"
                name="purchase-transfer-creation-mode"
                checked={purchaseTransferCreationMode === 'work_task'}
                onChange={() => setPurchaseTransferCreationMode('work_task')}
                className="mt-1 h-4 w-4"
              />
              <div>
                <div className="font-medium">{t?.purchasePostingFollowupTaskLabel ?? 'إنشاء مهمة عمل'}</div>
                <div className="text-xs text-muted-foreground">{t?.purchasePostingFollowupTaskDesc ?? 'إنشاء ارسالية بحالة معلقة لتظهر كـ مهمة عمل للموظف.'}</div>
              </div>
            </label>
            <label className="flex items-start gap-3 rounded-md border p-3 cursor-pointer">
              <input
                type="radio"
                name="purchase-transfer-creation-mode"
                checked={purchaseTransferCreationMode === 'none'}
                onChange={() => setPurchaseTransferCreationMode('none')}
                className="mt-1 h-4 w-4"
              />
              <div>
                <div className="font-medium">{t?.purchasePostingFollowupNoneLabel ?? 'بدون'}</div>
                <div className="text-xs text-muted-foreground">{t?.purchasePostingFollowupNoneDesc ?? 'لا يتم إنشاء ارسالية داخلية ولا مهمة عمل.'}</div>
              </div>
            </label>
          </div>
          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setPostingFollowupDialogOpen(false);
                setPendingPostingSubmit(null);
              }}
            >
              {t?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              disabled={isPending}
              onClick={() => {
                if (!pendingPostingSubmit) return;
                const pending = pendingPostingSubmit;
                const nextMode = purchaseTransferCreationMode;
                setPostingFollowupDialogOpen(false);
                setPendingPostingSubmit(null);
                submitWithPurchasePriceReview(pending, false, postingType, nextMode);
              }}
            >
              {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
              {t?.purchasePostingFollowupConfirm ?? 'تأكيد المتابعة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      )}
      <Dialog
        open={priceReviewDialogOpen}
        onOpenChange={(open) => {
          setPriceReviewDialogOpen(open);
          if (!open) {
            setPendingPriceReviewSubmission(null);
            setPriceReviewRows([]);
          }
        }}
      >
        <DialogContent className="max-h-[80vh] overflow-y-auto w-[96vw] max-w-5xl">
          <DialogHeader>
            <DialogTitle>{t?.purchasePriceReviewTitle ?? 'مراجعة أسعار الشراء قبل الحفظ'}</DialogTitle>
            <DialogDescription>
              {t?.purchasePriceReviewDescription ?? 'تم العثور على أصناف تغيّر فيها سعر الشراء عن آخر سعر شراء مسجل. راجعها قبل متابعة الحفظ.'}
            </DialogDescription>
          </DialogHeader>

          <div className="rounded-md border overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.item ?? 'الصنف'}</TableHead>
                  <TableHead className="text-end">{t?.lastPurchasePrice ?? 'آخر سعر شراء'}</TableHead>
                  <TableHead className="text-end">{t?.newPurchasePrice ?? 'السعر الجديد'}</TableHead>
                  <TableHead className="text-end">{t?.differenceLabel ?? 'الفرق'}</TableHead>
                  <TableHead>{t?.status ?? 'الحالة'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {priceReviewRows.map((row) => (
                  <TableRow key={row.materialId}>
                    <TableCell className="font-medium">{row.materialName}</TableCell>
                    <TableCell lang="en" dir="ltr" className="text-end font-mono">
                      {formatCurrency(row.previousPrice, displayCurrencySymbol)}
                      {row.previousCurrencyCode !== (watchedCurrencyCode || defaultBaseCurrencyCode) && (
                        <span className="ms-1 text-xs text-muted-foreground">
                          ({formatCurrency(row.previousOriginalPrice, currencies.find(c => c.code === row.previousCurrencyCode)?.symbol || row.previousCurrencyCode)} {row.previousCurrencyCode})
                        </span>
                      )}
                    </TableCell>
                    <TableCell lang="en" dir="ltr" className="text-end font-mono">{formatCurrency(row.newPrice, displayCurrencySymbol)}</TableCell>
                    <TableCell
                      lang="en"
                      dir="ltr"
                      className={cn('text-end font-mono', row.changeType === 'increase' ? 'text-emerald-700' : 'text-amber-700')}
                    >
                      {row.difference > 0 ? '+' : ''}{formatCurrency(row.difference, displayCurrencySymbol)}
                    </TableCell>
                    <TableCell>
                      <span className={cn('inline-flex rounded-full px-2 py-1 text-xs font-medium', row.changeType === 'increase' ? 'bg-emerald-100 text-emerald-800' : 'bg-amber-100 text-amber-800')}>
                        {row.changeType === 'increase'
                          ? (t?.priceIncreased ?? 'زيادة')
                          : (t?.priceDecreased ?? 'انخفاض')}
                      </span>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setPriceReviewDialogOpen(false);
                setPendingPriceReviewSubmission(null);
                setPriceReviewRows([]);
              }}
            >
              {t?.returnToEdit ?? 'الرجوع للتعديل'}
            </Button>
            <Button
              type="button"
              disabled={isPending}
              onClick={() => {
                if (!pendingPriceReviewSubmission) return;
                const submission = pendingPriceReviewSubmission;
                setPriceReviewDialogOpen(false);
                setPendingPriceReviewSubmission(null);
                setPriceReviewRows([]);
                submitOrder(
                  submission.data,
                  submission.allowDuplicateOverride,
                  submission.postingType,
                  submission.purchaseTransferCreationMode
                );
              }}
            >
              {t?.keepEnteredPrices ?? 'الاحتفاظ بالأسعار المدخلة والمتابعة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Card>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit, onInvalidSubmit)}
          onKeyDown={handleFormHotkeys}
          onFocusCapture={handleNumberInputFocusCapture}
          onMouseDownCapture={handleNumberInputMouseDownCapture}
        >
          <CardHeader>
            <CardTitle>{mode === 'edit' ? (t?.editTitle ?? 'تعديل أمر شراء') : (t?.title ?? 'أمر شراء')}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="rounded-md border p-3 space-y-3">
              <div className="flex items-center justify-between gap-3">
                <h3 className="text-base font-semibold">{t?.orderDetailsSection ?? 'تفاصيل أمر الشراء'}</h3>
                <div className="flex items-center gap-2">
                  <input
                    ref={documentInputRef}
                    type="file"
                    className="hidden"
                    multiple
                    onChange={(event) => handleUploadDocuments(event.target.files)}
                  />
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="h-8 px-2.5 text-xs"
                    onClick={handlePickDocuments}
                    disabled={isUploadingDocument || isPending}
                  >
                    <Paperclip className="me-2 h-4 w-4" />
                    {isUploadingDocument
                      ? (t?.uploadingDocuments ?? 'جارٍ رفع الوثائق...')
                      : (t?.attachDocuments ?? 'إرفاق وثائق')}
                  </Button>
                  {mode === 'edit' && (
                    (existingOrder?.postingStatus === 'posted') ||
                    (existingOrder?.documentType === 'shipment' && existingOrder?.postingStatus === 'saved')
                  ) && existingOrder?.purchaseTransferCreationMode === 'none' && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="h-8 px-2.5 text-xs"
                      disabled={isPending}
                      onClick={() => {
                        const fd = new FormData();
                        fd.append('purchaseOrderId', existingOrder.id);
                        fd.append('returnPath', `/admin/purchases/edit/${existingOrder.id}`);
                        startTransition(async () => { await handleCreateWorkTaskFromPurchaseOrder(fd); });
                      }}
                    >
                      {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : null}
                      {t?.createWorkTaskBtn ?? 'إنشاء مهمة عمل'}
                    </Button>
                  )}
                  {aiInvoiceEntryEnabled && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="h-8 px-2.5 text-xs"
                      onClick={() => setAiExtractionDialogOpen(true)}
                      disabled={isAiExtracting || isPending}
                    >
                      {isAiExtracting ? (
                        <>
                          <Loader2 className="me-2 h-4 w-4 animate-spin" />
                          {t?.analyzingInvoice ?? 'جارٍ التحليل...'}
                        </>
                      ) : (
                        <>
                          {t?.analyzeInvoiceAI ?? '🤖 تحليل ذكي'}
                        </>
                      )}
                    </Button>
                  )}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="h-8 px-2.5 text-xs"
                    onClick={() => setShowOrderHeaderDetails((prev) => !prev)}
                  >
                    {showOrderHeaderDetails ? (t?.hideDetails ?? 'إخفاء التفاصيل') : (t?.showDetails ?? 'إظهار التفاصيل')}
                    {showOrderHeaderDetails ? <ChevronUp className="ms-2 h-4 w-4" /> : <ChevronDown className="ms-2 h-4 w-4" />}
                  </Button>
                </div>
              </div>

              <div className="flex flex-wrap items-center gap-2 text-xs">
                <div className="inline-flex min-h-8 items-center gap-1.5 rounded-md border bg-muted/30 px-2">
                  <span className="text-muted-foreground">{t?.orderNumber ?? 'رقم الأمر'}:</span>
                  <span className="font-medium">{isDuplicatedDraft ? (t?.newOrderLabel ?? 'جديدة') : (mode === 'edit' ? (existingOrder?.orderNumber || '-') : (t?.newOrderLabel ?? 'جديدة'))}</span>
                </div>
                <div className="inline-flex min-h-8 items-center gap-1.5 rounded-md border bg-muted/30 px-2">
                  <span className="text-muted-foreground">{t?.orderDate ?? 'تاريخ الأمر'}:</span>
                  <span className="font-medium" suppressHydrationWarning>{orderDateLabel}</span>
                </div>
                <div className="inline-flex min-h-8 items-center gap-2 rounded-md border bg-muted/30 px-2">
                  <span className="text-muted-foreground">{t?.currencyLabel ?? 'العملة'}:</span>
                  <FormField
                    control={form.control}
                    name="currencyCode"
                    render={({ field }) => (
                      <Select
                        disabled={isFxLocked}
                        value={field.value}
                        onValueChange={(value) => {
                          field.onChange(value);
                          form.setValue('isAutoRate', true, { shouldDirty: true });
                          form.setValue('rateSource', configuredRateSource, { shouldDirty: true });
                          form.setValue('rateDate', defaultRateDate, { shouldDirty: true });
                          const selectedRate = Number(currencies.find((currency) => currency.code === value)?.exchangeRate || 0);
                          form.setValue('exchangeRate', value === defaultBaseCurrencyCode ? 1 : (Number.isFinite(selectedRate) && selectedRate > 0 ? selectedRate : 1), { shouldDirty: true });
                        }}
                      >
                        <FormControl>
                          <SelectTrigger className="h-7 min-w-[150px] border-0 bg-transparent px-1 text-xs shadow-none focus:ring-0 focus:ring-offset-0">
                            <SelectValue placeholder={t?.currencyLabel ?? 'العملة'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {currencies.map((cur) => (
                            <SelectItem key={cur.code} value={cur.code}>{`${cur.code} (${cur.symbol || ''})`}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  />
                </div>
                {!isBaseCurrency && (
                  <div className="inline-flex min-h-8 items-center gap-2 rounded-md border bg-muted/30 px-2">
                    <span className="text-muted-foreground">{t?.exchangeRateLabel ?? 'سعر الصرف'}:</span>
                    <FormField
                      control={form.control}
                      name="exchangeRate"
                      render={({ field }) => (
                        <Input
                          type="number"
                          step="0.0001"
                          min={0}
                          disabled
                          readOnly
                          value={field.value}
                          className="h-7 w-28 border-0 bg-transparent px-1 text-xs shadow-none focus-visible:ring-0"
                        />
                      )}
                    />
                  </div>
                )}
                {!isBaseCurrency && (
                  <div className="inline-flex min-h-8 items-center gap-2 rounded-md border bg-muted/30 px-2">
                    <span className="text-muted-foreground">{t?.rateDateLabel ?? 'تاريخ السعر'}:</span>
                    <FormField
                      control={form.control}
                      name="rateDate"
                      render={({ field }) => (
                        <Input type="date" className="h-7 w-36 border-0 bg-transparent px-1 text-xs shadow-none focus-visible:ring-0" disabled={isFxLocked} {...field} />
                      )}
                    />
                  </div>
                )}
              </div>

              {orderDocuments.length > 0 && (
                <div className="rounded-md border bg-muted/20 p-2">
                  <div className="mb-2 text-xs text-muted-foreground">
                    {(t?.attachedDocuments || 'الوثائق المرفقة')}: {orderDocuments.length}
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {orderDocuments.map((doc) => (
                      <div key={doc.id} className="inline-flex items-center gap-2 rounded-md border bg-background px-2 py-1 text-xs">
                        <FileText className="h-3.5 w-3.5 text-muted-foreground" />
                        {mode === 'edit' && existingOrder?.id ? (
                          <a
                            className="max-w-[220px] truncate underline text-primary"
                            href={`/api/admin/purchases/documents?filePath=${encodeURIComponent(doc.filePath)}&name=${encodeURIComponent(doc.name)}`}
                            target="_blank"
                            rel="noreferrer"
                          >
                            {doc.name}
                          </a>
                        ) : (
                          <span className="max-w-[220px] truncate">{doc.name}</span>
                        )}
                        <button
                          type="button"
                          className="text-destructive hover:underline"
                          onClick={() => removeDocument(doc.id)}
                        >
                          {tGlobal?.remove ?? 'إزالة'}
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Document Type Toggle — Shipment Workflow */}
              {shipmentWorkflowEnabled && (
                <div className="flex flex-wrap items-center gap-3 pt-1">
                  <span className="text-sm font-medium">{t?.documentTypeLabel ?? 'نوع المستند'}:</span>
                  <div className="inline-flex overflow-hidden rounded-md border divide-x rtl:divide-x-reverse">
                    <button
                      type="button"
                      className={cn(
                        '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');
                        if (postingType === 'posted') {
                          setPostingType('saved');
                        }
                      }}
                    >
                      {t?.shipmentDocLabel ?? 'ارسالية'}
                    </button>
                    <button
                      type="button"
                      className={cn(
                        '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')}
                    >
                      {t?.taxInvoiceDocLabel ?? 'فاتورة ضريبية'}
                    </button>
                  </div>
                  {documentType === 'shipment' && (
                    <span className="rounded border border-amber-200 bg-amber-50 px-2 py-0.5 text-xs text-amber-700">
                      {t?.shipmentNoteLabel ?? 'عند الحفظ: يؤثر على المخزون وينشئ مسودة قيد GRNI للمراجعة'}
                    </span>
                  )}
                </div>
              )}

              {showOrderHeaderDetails ? (
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3">

                  <FormField
                    control={form.control}
                    name="supplierId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.selectParty ?? 'اختر مورداً أو زبوناً...'}</FormLabel>
                        <FormControl>
                          <PartySelector
                            value={selectedPartyId}
                            open={popoverOpen}
                            onOpenChange={setPopoverOpen}
                            placeholder={t?.selectParty ?? 'اختر مورداً أو زبوناً...'}
                            searchPlaceholder={t?.searchParty ?? 'ابحث عن مورد أو زبون...'}
                            options={parties.map((party) => ({
                              id: party.id,
                              label: party.name,
                              description: `(${party.type === 'supplier' ? t?.supplierLabel ?? 'مورد' : t?.customerLabel ?? 'زبون'})`,
                              searchableText: `${party.type} ${party.name}`,
                            }))}
                            onValueChange={(partyId) => {
                              const party = parties.find((entry) => entry.id === partyId);
                              if (!party) return;
                              field.onChange(party.originalId);
                              setSelectedPartyId(party.id);
                            }}
                            footerAction={
                              <Button
                                type="button"
                                variant="outline"
                                className="w-full"
                                onClick={() => {
                                  blurActiveElement();
                                  setShowAddSupplierDialog(true);
                                }}
                              >
                                {t?.addSupplierButton ?? 'إضافة مورد جديد'}
                              </Button>
                            }
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <div className="space-y-2">
                    <label className="text-sm font-medium">{t?.supplierInvoiceNumber ?? 'رقم فاتورة المورد'}</label>
                    <Input
                      placeholder={t?.supplierInvoiceNumberPlaceholder ?? 'أدخل رقم فاتورة المورد'}
                      className="h-9"
                      {...form.register('supplierInvoiceNumber', {
                        onBlur: (event) => {
                          const value = String(event.target.value || '').trim();
                          if (!selectedPartyInfo) {
                            setSupplierInvoiceDuplicateInfo(null);
                            return;
                          }

                          const duplicate = findDuplicateInvoice(selectedPartyInfo.id, value);
                          setSupplierInvoiceDuplicateInfo(duplicate);

                          if (!form.getValues('allowDuplicateInvoice') && duplicate) {
                            setDuplicateInfo(duplicate);
                            setPendingSubmit(form.getValues());
                            setDuplicateDialogOpen(true);
                          }
                        },
                      })}
                    />
                    {supplierInvoiceDuplicateInfo && (
                      <p className="text-xs text-amber-600">
                        {(t?.duplicateInvoiceStatusHint ?? 'رقم فاتورة المورد موجود مسبقًا. حالة السند: {status}.')
                          .replace('{status}', getOrderStatusLabel(supplierInvoiceDuplicateInfo))}
                      </p>
                    )}
                    {form.formState.errors.supplierInvoiceNumber?.message ? (
                      <p className="text-sm font-medium text-destructive">{String(form.formState.errors.supplierInvoiceNumber.message)}</p>
                    ) : null}
                  </div>

                  <FormField
                    control={form.control}
                    name="supplierInvoiceDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.supplierInvoiceDate ?? 'تاريخ فاتورة المورد'}</FormLabel>
                        <FormControl>
                          <Input type="date" className="h-9" {...field} value={field.value ?? defaultRateDate} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {isWarehouseEnabled && (
                    <FormField
                      control={form.control}
                      name="warehouseId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>{t?.warehouseLabel ?? 'المستودع'}</FormLabel>
                          <Select
                            onValueChange={(value) => {
                              field.onChange(value);
                              const shelves = shelvesByWarehouse.get(value) ?? [];
                              const nextShelfId = defaultShelfId || shelves[0]?.id || '';

                              form.setValue('items', form.getValues('items').map((item) => ({
                                ...item,
                                warehouseId: value,
                                shelfId: nextShelfId,
                              })));

                              setGridItems((prev) => prev.map((item) => ({
                                ...item,
                                warehouseId: value,
                                shelfId: nextShelfId,
                              })));
                            }}
                            value={field.value || ''}
                          >
                            <FormControl>
                              <SelectTrigger className="h-9 text-sm">
                                <SelectValue placeholder={t?.warehouseLabel ?? 'المستودع'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {warehouses.map((warehouse) => (
                                <SelectItem key={warehouse.id} value={warehouse.id}>{warehouse.name}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  )}

                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-3 gap-2 text-xs text-muted-foreground">
                  <div>{t?.selectParty ?? 'الطرف'}: {selectedParty?.name || '-'}</div>
                  <div>{t?.currencyLabel ?? 'العملة'}: {watchedCurrencyCode || '-'}</div>
                  <div>{t?.warehouseLabel ?? 'المستودع'}: {warehouses.find((w) => w.id === watchedWarehouseId)?.name || '-'}</div>
                </div>
              )}
            </div>

            {isRealEstateEnabled && (
              <div className="rounded-md border bg-muted/10 p-3 space-y-3">
              <div>
                <p className="text-sm font-medium">{t?.realEstatePurchaseLinkTitle ?? 'ربط الفاتورة بالمشروع العقاري'}</p>
                <p className="text-xs text-muted-foreground">
                  {t?.realEstatePurchaseLinkDesc ?? 'حدد المبنى أولًا، ثم اختر هل الفاتورة تخص المبنى كاملًا أو ستوزع على أسطر الفاتورة بحسب الطابق أو الجزء.'}
                </p>
              </div>

              <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                <FormField
                  control={form.control}
                  name="realEstateLinkMode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.realEstateLinkModeLabel ?? 'طريقة الربط'}</FormLabel>
                      <Select onValueChange={field.onChange} value={field.value || 'none'}>
                        <FormControl>
                          <SelectTrigger className="h-9 text-sm">
                            <SelectValue placeholder={t?.realEstateLinkModeLabel ?? 'طريقة الربط'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="none">{t?.noRealEstateLinkOption ?? 'بدون ربط عقاري'}</SelectItem>
                          <SelectItem value="order">{t?.fullInvoiceProjectOption ?? 'الفاتورة تخص المبنى/الطابق كاملًا'}</SelectItem>
                          <SelectItem value="line-items">{t?.lineItemsProjectOption ?? 'كل سطر يتبع لطابق/جزء مختلف'}</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="realEstateProjectId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.realEstateProjectLabel ?? 'المبنى / المشروع'}</FormLabel>
                      <Select
                        onValueChange={(value) => {
                          field.onChange(value);
                          const selectedProjectName = String(realEstateProjectsById.get(value)?.name || '');
                          form.setValue('realEstateProjectName', selectedProjectName, { shouldDirty: true, shouldValidate: false });
                        }}
                        value={field.value || ''}
                      >
                        <FormControl>
                          <SelectTrigger data-real-estate-header-field="project" className="h-9 text-sm">
                            <SelectValue placeholder={t?.selectRealEstateProjectPlaceholder ?? 'اختر المبنى'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {realEstateProjects.length === 0 ? (
                            <SelectItem value="__none__" disabled>{t?.noRealEstateProjects ?? 'لا توجد مشاريع عقارية محفوظة'}</SelectItem>
                          ) : (
                            realEstateProjects.map((project) => (
                              <SelectItem key={project.id} value={project.id}>{project.name}</SelectItem>
                            ))
                          )}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {watchedRealEstateLinkMode === 'order' && (
                  <FormField
                    control={form.control}
                    name="realEstateScope"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.realEstateScopeLabel ?? 'نطاق الفاتورة'}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value || 'project'}>
                          <FormControl>
                            <SelectTrigger className="h-9 text-sm">
                              <SelectValue placeholder={t?.realEstateScopeLabel ?? 'نطاق الفاتورة'} />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="project">{t?.fullBuildingOption ?? 'المبنى كاملًا'}</SelectItem>
                            <SelectItem value="floor">{t?.singleFloorOption ?? 'طابق محدد'}</SelectItem>
                            <SelectItem value="part">{t?.floorPartOption ?? 'جزء من طابق'}</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {watchedRealEstateLinkMode !== 'none' && (watchedRealEstateScope === 'project' || watchedRealEstateLinkMode === 'line-items') && (
                  <FormField
                    control={form.control}
                    name="realEstateAllocationMethod"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.allocationMethodLabel ?? 'أساس توزيع المصروف المشترك'}</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value || 'area'}>
                          <FormControl>
                            <SelectTrigger className="h-9 text-sm">
                              <SelectValue placeholder={t?.allocationMethodLabel ?? 'أساس التوزيع'} />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="area">{t?.allocateByAreaLabel ?? 'حسب المساحة'}</SelectItem>
                            <SelectItem value="sale-value">{t?.allocateBySaleValueLabel ?? 'حسب القيمة البيعية'}</SelectItem>
                            <SelectItem value="manual-share">{t?.allocateByManualShareLabel ?? 'حسب النسبة اليدوية'}</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-[11px] text-muted-foreground">
                          {watchedRealEstateLinkMode === 'line-items'
                            ? (t?.realEstateSharedAllocationHint ?? 'أي سطر تختار له "المبنى كاملًا" سيُعامل كمصروف مشترك ويُوزع بهذه الطريقة.')
                            : (t?.realEstateSharedAllocationHint ?? 'عند اختيار "المبنى كاملًا" تُعامل الفاتورة كمصروف مشترك مثل تبويب التكاليف المشتركة.')}
                        </p>
                        {watchedRealEstateAllocationMethod === 'area' && (
                          <p className="text-[11px] text-sky-700">
                            {selectedProjectAllocationStats.totalArea > 0
                              ? `${t?.areaAllocationProjectHint ?? 'سيتم الاعتماد على حقل المساحة (م²) لكل وحدة داخل بيانات المشروع.'} ${selectedProjectAllocationStats.totalArea.toFixed(2)} م²`
                              : (t?.areaAllocationMissingHint ?? 'سيتم الاعتماد على حقل المساحة (م²) لكل وحدة، لذا تأكد من تعبئة المساحات داخل التفاصيل الهندسية للمشروع.')}
                          </p>
                        )}
                        {watchedRealEstateAllocationMethod === 'sale-value' && (
                          <p className={`text-[11px] ${selectedProjectAllocationStats.totalSaleValue > 0 ? 'text-emerald-700' : 'text-amber-700'}`}>
                            {selectedProjectAllocationStats.totalSaleValue > 0
                              ? `${t?.saleValueAllocationProjectHint ?? 'سيتم الاعتماد على القيم البيعية التقديرية للوحدات المسجلة داخل بيانات المشروع.'} ${formatCurrency(selectedProjectAllocationStats.totalSaleValue, currencySymbol)}`
                              : (t?.saleValueAllocationMissingHint ?? 'يلزم تعبئة حقل القيمة البيعية التقديرية داخل تفاصيل وحدات المشروع حتى يعمل التوزيع حسب القيمة البيعية بشكل صحيح.')}
                          </p>
                        )}
                        {watchedRealEstateAllocationMethod === 'manual-share' && (
                          <p className={`text-[11px] ${Math.abs(selectedProjectAllocationStats.manualShareTotal - 100) <= 0.01 ? 'text-emerald-700' : 'text-amber-700'}`}>
                            {(t?.manualShareProjectHint ?? 'سيتم استخدام نسب التوزيع اليدوية المحفوظة داخل بيانات المشروع.')} {selectedProjectAllocationStats.manualShareTotal.toFixed(2)}%
                          </p>
                        )}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {watchedRealEstateLinkMode === 'order' && watchedRealEstateScope !== 'project' && (
                  <FormField
                    control={form.control}
                    name="realEstateFloorLabel"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t?.realEstateFloorLabel ?? 'الطابق'}</FormLabel>
                        {realEstateFloorOptions.length > 0 ? (
                          <Select
                            onValueChange={(value) => {
                              field.onChange(value);
                              if (watchedRealEstateScope === 'part') {
                                const partOptions = getRealEstatePartOptions(value);
                                form.setValue('realEstatePartLabel', partOptions[0]?.value || '', { shouldDirty: true, shouldValidate: false });
                              }
                            }}
                            value={field.value || ''}
                          >
                            <FormControl>
                              <SelectTrigger className="h-9 text-sm">
                                <SelectValue placeholder={t?.realEstateFloorPlaceholder ?? 'اختر الطابق'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {realEstateFloorOptions.map((floor) => (
                                <SelectItem key={floor.id} value={floor.value}>
                                  {floor.helperText ? `${floor.label} — ${floor.helperText}` : floor.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        ) : (
                          <FormControl>
                            <Input
                              className="h-9"
                              placeholder={selectedRealEstateProject?.floorDetails?.[0]?.floorLabel || (t?.realEstateFloorPlaceholder ?? 'مثل: الطابق 2')}
                              {...field}
                            />
                          </FormControl>
                        )}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {watchedRealEstateLinkMode === 'order' && watchedRealEstateScope === 'part' && (
                  <FormField
                    control={form.control}
                    name="realEstatePartLabel"
                    render={({ field }) => {
                      const partOptions = getRealEstatePartOptions(form.getValues('realEstateFloorLabel'));
                      return (
                        <FormItem className="md:col-span-2 xl:col-span-4">
                          <FormLabel>{t?.realEstatePartLabel ?? 'الجزء / الجهة'}</FormLabel>
                          {partOptions.length > 0 ? (
                            <Select onValueChange={field.onChange} value={field.value || ''}>
                              <FormControl>
                                <SelectTrigger className="h-9 text-sm">
                                  <SelectValue placeholder={t?.realEstatePartPlaceholder ?? 'اختر الجزء أو الوحدة'} />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                {partOptions.map((part, partIndex) => (
                                  <SelectItem key={`${part.value}-${partIndex}`} value={part.value}>{part.label}</SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          ) : (
                            <FormControl>
                              <Input
                                className="h-9"
                                placeholder={t?.realEstatePartPlaceholder ?? 'مثل: الواجهة الشمالية، المحلات الأمامية، أو منطقة الخدمات'}
                                {...field}
                              />
                            </FormControl>
                          )}
                          <FormMessage />
                        </FormItem>
                      );
                    }}
                  />
                )}
              </div>

              {watchedRealEstateLinkMode === 'line-items' && (
                <div className="space-y-2">
                  <p className="text-[11px] text-muted-foreground">
                    {t?.realEstateLineItemsHint ?? 'سيظهر عمود جديد داخل الفاتورة لتحديد تبعية كل سطر: المبنى كاملًا، طابق معين، أو جزء من طابق.'}
                  </p>
                  {lineItemTargetingSummary && (
                    <button
                      type="button"
                      onClick={() => lineItemTargetingSummary.issues.length > 0 && focusFirstIncompleteLineItemTarget()}
                      className={`w-full rounded-md border px-2.5 py-2 text-[11px] text-start ${lineItemTargetingSummary.issues.length > 0 ? 'border-amber-300 bg-amber-50 text-amber-900 hover:bg-amber-100' : 'border-emerald-300 bg-emerald-50 text-emerald-900'} ${lineItemTargetingSummary.issues.length > 0 ? 'cursor-pointer' : 'cursor-default'}`}
                      disabled={lineItemTargetingSummary.issues.length === 0}
                    >
                      <div className="font-medium">
                        {t?.lineItemSummaryTitle ?? 'ملخص ربط الأسطر'}: {t?.lineLabel ?? 'عدد الأسطر'} {lineItemTargetingSummary.total}
                        {' • '}{t?.fullBuildingOption ?? 'المبنى كاملًا'} {lineItemTargetingSummary.projectCount}
                        {' • '}{t?.singleFloorOption ?? 'طابق محدد'} {lineItemTargetingSummary.floorCount}
                        {' • '}{t?.floorPartOption ?? 'جزء من طابق'} {lineItemTargetingSummary.partCount}
                      </div>
                      {lineItemTargetingSummary.issues.length > 0 ? (
                        <div className="mt-1">
                          {lineItemTargetingSummary.issues.slice(0, 3).join(' | ')}
                          {lineItemTargetingSummary.issues.length > 3 ? ` (+${lineItemTargetingSummary.issues.length - 3})` : ''}
                        </div>
                      ) : (
                        <div className="mt-1">{t?.lineItemSummaryValid ?? 'جميع الأسطر مكتملة وجاهزة للحفظ.'}</div>
                      )}
                    </button>
                  )}
                </div>
              )}
            </div>
            )}

            <Tabs defaultValue="items" className="space-y-4">
              <InvoiceTabsNav
                isRtl={isRtlLayout}
                itemsLabel={t?.itemDetailsTabLabel ?? 'تفاصيل الاصناف'}
                paymentLabel={t?.paymentTabLabel ?? 'الدفع'}
                notesLabel={t?.notesLabel ?? 'ملاحظات'}
                logLabel={t?.logLabel ?? 'log'}
              />

              <TabsContent value="items" forceMount className="space-y-4 data-[state=inactive]:hidden">

                {/* Shipment Linker — Tax Invoice mode */}
                {shipmentWorkflowEnabled && documentType === 'tax_invoice' && (
                  <div className="rounded-md border bg-muted/20 p-3 space-y-2">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="text-sm font-semibold">{t?.linkedShipmentsLabel ?? 'الارساليات المرتبطة'}</span>
                      {linkedShipmentIds.length > 0 && (
                        <span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                          {linkedShipmentIds.length}
                        </span>
                      )}
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        className="h-7 px-2.5 text-xs ms-auto"
                        disabled={!selectedPartyInfo || isLoadingShipments}
                        onClick={async () => {
                          if (!selectedPartyInfo) return;
                          setShipmentPanelOpen((prev) => !prev);
                          if (!shipmentPanelOpen && availableShipments.length === 0) {
                            setIsLoadingShipments(true);
                            try {
                              const result = await getUnlinkedPurchaseShipmentsBySupplier(selectedPartyInfo.id);
                              const rows = Array.isArray(result)
                                ? (result as PurchaseOrder[])
                                : (Array.isArray((result as any)?.orders) ? ((result as any).orders as PurchaseOrder[]) : []);
                              setAvailableShipments(rows);
                            } finally {
                              setIsLoadingShipments(false);
                            }
                          }
                        }}
                      >
                        {isLoadingShipments ? (
                          <Loader2 className="h-3.5 w-3.5 animate-spin me-1" />
                        ) : null}
                        {shipmentPanelOpen
                          ? (t?.hideShipmentsPanel ?? 'إخفاء الارساليات')
                          : (t?.showShipmentsPanel ?? 'ربط ارساليات سابقة')}
                      </Button>
                    </div>

                    {/* Linked shipment badges */}
                    {linkedShipmentIds.length > 0 && (
                      <div className="flex flex-wrap gap-1.5">
                        {linkedShipmentIds.map((shipId) => {
                          const shipment = availableShipments.find((s) => s.id === shipId);
                          return (
                            <span
                              key={shipId}
                              className="inline-flex items-center gap-1 rounded-full border border-amber-300 bg-amber-50 px-2.5 py-0.5 text-xs text-amber-800"
                            >
                              {shipment ? `#${shipment.orderNumber}` : shipId}
                              <button
                                type="button"
                                className="ms-0.5 rounded-full hover:text-destructive"
                                onClick={() => setLinkedShipmentIds((prev) => prev.filter((id) => id !== shipId))}
                              >
                                <X className="h-3 w-3" />
                              </button>
                            </span>
                          );
                        })}
                      </div>
                    )}

                    {/* Shipment picker panel */}
                    {shipmentPanelOpen && (
                      <div className="rounded-md border bg-background p-2 space-y-1 max-h-56 overflow-y-auto">
                        {availableShipments.length === 0 && !isLoadingShipments && (
                          <p className="py-3 text-center text-sm text-muted-foreground">
                            {t?.noUnlinkedShipments ?? 'لا توجد ارساليات غير مرتبطة لهذا المورد.'}
                          </p>
                        )}
                        {availableShipments.map((shipment) => {
                          const isLinked = linkedShipmentIds.includes(shipment.id);
                          return (
                            <label
                              key={shipment.id}
                              className={cn(
                                'flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-sm transition-colors hover:bg-muted/60',
                                isLinked && 'bg-amber-50'
                              )}
                            >
                              <input
                                type="checkbox"
                                className="h-4 w-4 rounded border-input"
                                checked={isLinked}
                                onChange={(e) => {
                                  const checked = e.target.checked;
                                  setLinkedShipmentIds((prev) =>
                                    checked
                                      ? [...prev, shipment.id]
                                      : prev.filter((id) => id !== shipment.id)
                                  );
                                  if (checked && shipment.items) {
                                    // Auto-import items from the linked shipment
                                    const headerWh = isWarehouseEnabled ? (watchedWarehouseId || defaultWarehouseId) : '';
                                    const newItems = (shipment.items || []).map((item) => ({
                                      materialId: item.materialId,
                                      quantity: item.quantity,
                                      unitPrice: item.unitPrice,
                                      lineDiscountPercent: item.lineDiscountPercent || 0,
                                      lineDiscountAmount: item.lineDiscountAmount || 0,
                                      bonus: item.bonus || 0,
                                      warehouseId: isWarehouseEnabled ? (item.warehouseId || headerWh) : '',
                                      shelfId: isWarehouseEnabled ? (item.shelfId || '') : '',
                                      taxRate: item.taxRate || 0,
                                      realEstateProjectId: '',
                                      realEstateProjectName: '',
                                      realEstateFloorLabel: '',
                                      realEstatePartLabel: '',
                                    }));
                                    setGridItems((prev) => [...prev.filter((gi) => gi.materialId), ...newItems]);
                                  }
                                }}
                              />
                              <span className="flex-1 font-medium">#{shipment.orderNumber}</span>
                              <span className="text-muted-foreground text-xs">
                                {shipment.date ? format(new Date(shipment.date), 'yyyy-MM-dd') : ''}
                              </span>
                              <span className="text-xs font-medium">
                                {formatCurrency(shipment.grandTotal || 0, displayCurrencySymbol)}
                              </span>
                            </label>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}

                {/* Items Section */}
                <div dir={isRtlLayout ? 'rtl' : 'ltr'} className="rounded-md border p-4">
              <div className="mt-4 mb-4">
                <label className="text-sm font-medium">{t?.scanBarcode ?? 'مسح الباركود'}</label>
                <input
                  type="text"
                  value={barcodeInput}
                  onChange={(e) => setBarcodeInput(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && barcodeInput.trim()) {
                      e.preventDefault();
                      handleBarcodeScanned(barcodeInput.trim());
                    }
                  }}
                  autoFocus
                  placeholder={t?.barcodePlaceholder ?? 'امسح الباركود أو أدخله هنا...'}
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base text-start ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
                />
                <div className="mt-2 flex flex-wrap items-center gap-x-6 gap-y-2">
                  <div className="flex items-center gap-2">
                    <input
                      id="update-sale-price"
                      type="checkbox"
                      className="h-4 w-4"
                      checked={autoUpdateSalePrice}
                      onChange={(event) => setAutoUpdateSalePrice(event.target.checked)}
                    />
                    <label htmlFor="update-sale-price" className="text-sm">
                      {t?.updateSalePriceOnPurchaseChange ?? 'تغيير سعر البيع عند تغيير سعر الشراء'}
                    </label>
                  </div>
                  <div className="flex items-center gap-2">
                    <input
                      id="toggle-item-description"
                      type="checkbox"
                      className="h-4 w-4"
                      checked={showItemDescriptions}
                      onChange={(event) => setShowItemDescriptions(event.target.checked)}
                    />
                    <label htmlFor="toggle-item-description" className="text-sm">
                      {t?.showItemDescription ?? 'عرض اسم الصنف تحت السطر'}
                    </label>
                  </div>
                  <div className="ms-auto">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button type="button" variant="outline" size="sm" className="h-8 gap-1 px-2.5 text-xs">
                          <SlidersHorizontal className="h-3.5 w-3.5" />
                          <span>{t?.tableOptionsLabel ?? 'الأعمدة'}</span>
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="w-44">
                        {isWarehouseEnabled && (
                          <DropdownMenuCheckboxItem
                            checked={columnVisibility.shelf}
                            onCheckedChange={(checked) => setColumnVisibility((prev) => ({ ...prev, shelf: Boolean(checked) }))}
                          >
                            {t?.shelfLabel ?? 'الرف'}
                          </DropdownMenuCheckboxItem>
                        )}
                        <DropdownMenuCheckboxItem
                          checked={columnVisibility.discountPercent}
                          onCheckedChange={(checked) => setColumnVisibility((prev) => ({ ...prev, discountPercent: Boolean(checked) }))}
                        >
                          {t?.lineDiscountPercent ?? 'خصم %'}
                        </DropdownMenuCheckboxItem>
                        <DropdownMenuCheckboxItem
                          checked={columnVisibility.discountAmount}
                          onCheckedChange={(checked) => setColumnVisibility((prev) => ({ ...prev, discountAmount: Boolean(checked) }))}
                        >
                          {t?.lineDiscountAmount ?? 'خصم'}
                        </DropdownMenuCheckboxItem>
                        <DropdownMenuCheckboxItem
                          checked={columnVisibility.bonus}
                          onCheckedChange={(checked) => setColumnVisibility((prev) => ({ ...prev, bonus: Boolean(checked) }))}
                        >
                          {t?.bonus ?? 'بونص'}
                        </DropdownMenuCheckboxItem>
                        <DropdownMenuCheckboxItem
                          checked={columnVisibility.total}
                          onCheckedChange={(checked) => setColumnVisibility((prev) => ({ ...prev, total: Boolean(checked) }))}
                        >
                          {t?.total ?? 'الإجمالي'}
                        </DropdownMenuCheckboxItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </div>
              </div>

              <div className="mt-4">
                <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]">#</TableHead>
                      <TableHead className={cn("group relative", resizingColumnKey === 'item' && 'bg-emerald-50')} style={{ width: `${columnWidths.item}px`, minWidth: `${columnWidths.item}px` }}>
                        {t?.item ?? 'الصنف'}
                        {renderResizeHandle('item')}
                      </TableHead>
                      {hasRealEstateLineColumn && <TableHead className="w-[220px] min-w-[220px]">{t?.realEstateTargetColumn ?? 'يتبع إلى'}</TableHead>}
                      <TableHead className={cn("group relative", resizingColumnKey === 'quantity' && 'bg-emerald-50')} style={{ width: `${columnWidths.quantity}px`, minWidth: `${columnWidths.quantity}px` }}>
                        {t?.quantity ?? 'الكمية'}
                        {renderResizeHandle('quantity')}
                      </TableHead>
                      <TableHead className={cn("group relative", resizingColumnKey === 'price' && 'bg-emerald-50')} style={{ width: `${columnWidths.price}px`, minWidth: `${columnWidths.price}px` }}>
                        {t?.price ?? 'السعر'}
                        {renderResizeHandle('price')}
                      </TableHead>
                      {isShelfColumnVisible && <TableHead className={cn("group relative", resizingColumnKey === 'shelf' && 'bg-emerald-50')} style={{ width: `${columnWidths.shelf}px`, minWidth: `${columnWidths.shelf}px` }}>{t?.shelfLabel ?? 'الرف'}{renderResizeHandle('shelf')}</TableHead>}
                      {columnVisibility.discountPercent && <TableHead className={cn("group relative", resizingColumnKey === 'discountPercent' && 'bg-emerald-50')} style={{ width: `${columnWidths.discountPercent}px`, minWidth: `${columnWidths.discountPercent}px` }}>{t?.lineDiscountPercent ?? 'خصم %'}{renderResizeHandle('discountPercent')}</TableHead>}
                      {columnVisibility.discountAmount && <TableHead className={cn("group relative", resizingColumnKey === 'discountAmount' && 'bg-emerald-50')} style={{ width: `${columnWidths.discountAmount}px`, minWidth: `${columnWidths.discountAmount}px` }}>{t?.lineDiscountAmount ?? 'خصم'}{renderResizeHandle('discountAmount')}</TableHead>}
                      {columnVisibility.bonus && <TableHead className={cn("group relative", resizingColumnKey === 'bonus' && 'bg-emerald-50')} style={{ width: `${columnWidths.bonus}px`, minWidth: `${columnWidths.bonus}px` }}>{t?.bonus ?? 'بونص'}{renderResizeHandle('bonus')}</TableHead>}
                      {columnVisibility.total && <TableHead className={cn("group relative text-end", resizingColumnKey === 'total' && 'bg-emerald-50')} style={{ width: `${columnWidths.total}px`, minWidth: `${columnWidths.total}px` }}>{t?.total ?? 'الإجمالي'}{renderResizeHandle('total')}</TableHead>}
                      <TableHead className="w-[120px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {gridItems.map((item, index) => {
                      const itemCol = editableColumns.item;
                      const quantityCol = editableColumns.quantity;
                      const priceCol = editableColumns.price;
                      const shelfCol = editableColumns.shelf;
                      const discountPercentCol = editableColumns.discountPercent;
                      const discountAmountCol = editableColumns.discountAmount;
                      const bonusCol = editableColumns.bonus;
                      const totalCol = editableColumns.total;
                      const material = materialsById.get(item.materialId);
                      const description = material?.name?.trim();
                      const itemSymbolName = (material?.itemSymbolName || '').trim();
                      const rowRealEstateScope = item.realEstateScope || 'project';
                      const rowWarehouseId = isWarehouseEnabled
                        ? (headerWarehouseId || item.warehouseId || existingOrder?.warehouseId || '')
                        : '';
                      const rowTargetingIssues = lineItemTargetingIssuesByRow.get(index);
                      const prioritizedRowShelves = isWarehouseEnabled
                        ? getPrioritizedShelves(item.materialId, rowWarehouseId)
                        : [];

                      return (
                        <Fragment key={index}>
                          <TableRow
                            className={cn(
                              "transition-colors",
                              draggingRowIndex === index && "opacity-60",
                              activeGridRowIndex === index && "bg-emerald-50/80",
                              rowTargetingIssues && "bg-amber-50/40"
                            )}
                            onFocusCapture={() => setActiveGridRowIndex(index)}
                            onDragOver={(event) => event.preventDefault()}
                            onDrop={(event) => {
                              event.preventDefault();
                              if (draggingRowIndex === null || draggingRowIndex === index) {
                                setDraggingRowIndex(null);
                                return;
                              }
                              moveGridRow(draggingRowIndex, index);
                              setDraggingRowIndex(null);
                              setTimeout(() => focusCell(index, Math.max(0, itemCol)), 0);
                            }}
                            onBlurCapture={(event) => {
                              if (event.currentTarget.contains(event.relatedTarget as Node | null)) {
                                return;
                              }
                              setActiveGridRowIndex((current) => (current === index ? null : current));
                            }}
                          >
                            <TableCell className="text-center text-xs text-muted-foreground align-middle">
                              <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={t?.dragToReorder ?? 'اسحب لنقل السطر'}
                                  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 className="align-middle" style={{ width: `${columnWidths.item}px`, minWidth: `${columnWidths.item}px` }}>
                              <button
                                type="button"
                                data-cell={`${index}-${itemCol}`}
                                className={`w-full min-w-0 h-10 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 ${item.materialId ? '' : 'text-muted-foreground'}`}
                                onClick={() => {
                                  setPickerTargetRowIndex(index);
                                  blurActiveElement();
                                  setShowItemPicker(true);
                                  setItemPickerQuery('');
                                  setItemPickerInputResetKey((prev) => prev + 1);
                                }}
                                onContextMenu={(event) => {
                                  if (!item.materialId) return;
                                  event.preventDefault();
                                  setItemContextMenu({ x: event.clientX, y: event.clientY, materialId: item.materialId });
                                }}
                                onKeyDown={(event) => handleGridKeyDown(event as any, index, itemCol)}
                              >
                                <span className="truncate">
                                  {item.materialId
                                    ? (material?.name ?? item.materialId)
                                    : (t?.selectItem ?? 'اختر الصنف')}
                                </span>
                                <ChevronDown className="h-3.5 w-3.5 shrink-0 ms-auto opacity-50" />
                              </button>
                            </TableCell>
                            {hasRealEstateLineColumn && (
                              <TableCell className="align-top min-w-[220px]">
                                <div className="space-y-1">
                                  <select
                                    data-real-estate-row={index}
                                    data-real-estate-field="scope"
                                    className={cn(
                                      "w-full min-w-0 h-9 rounded-md border px-2 py-1 text-xs focus:ring-2 focus:ring-ring",
                                      rowTargetingIssues?.scope && "border-amber-500 bg-amber-50 text-amber-900"
                                    )}
                                    value={rowRealEstateScope}
                                    disabled={!watchedRealEstateProjectId}
                                    onChange={(event) => {
                                      const value = event.target.value as 'project' | 'floor' | 'part';
                                      const defaultFloorLabel = realEstateFloorOptions[0]?.value || '';
                                      setGridItems((prev) => {
                                        const next = [...prev];
                                        const resolvedFloorLabel = value === 'project' ? '' : (next[index].realEstateFloorLabel || defaultFloorLabel);
                                        const partOptions = getRealEstatePartOptions(resolvedFloorLabel);
                                        next[index] = {
                                          ...next[index],
                                          realEstateProjectId: watchedRealEstateProjectId || '',
                                          realEstateProjectName: selectedRealEstateProject?.name || '',
                                          realEstateScope: value,
                                          realEstateFloorLabel: resolvedFloorLabel,
                                          realEstatePartLabel: value === 'part' ? (next[index].realEstatePartLabel || partOptions[0]?.value || '') : '',
                                          realEstateAllocationMethod: value === 'project'
                                            ? (next[index].realEstateAllocationMethod || watchedRealEstateAllocationMethod || 'area')
                                            : undefined,
                                        };
                                        return next;
                                      });
                                    }}
                                  >
                                    <option value="project">{t?.fullBuildingOption ?? 'المبنى كاملًا'}</option>
                                    <option value="floor">{t?.singleFloorOption ?? 'طابق محدد'}</option>
                                    <option value="part">{t?.floorPartOption ?? 'جزء من طابق'}</option>
                                  </select>
                                  {rowRealEstateScope === 'project' && (
                                    <div className={cn(
                                      "rounded-md px-2 py-1 text-[11px]",
                                      rowTargetingIssues?.allocation
                                        ? "border border-amber-500 bg-amber-100 text-amber-900"
                                        : "bg-amber-50 text-amber-800"
                                    )}>
                                      {(t?.sharedCostPurchaseHint ?? 'مصروف مشترك')} — {watchedRealEstateAllocationMethod === 'sale-value'
                                        ? (t?.allocateBySaleValueLabel ?? 'حسب القيمة البيعية')
                                        : watchedRealEstateAllocationMethod === 'manual-share'
                                          ? (t?.allocateByManualShareLabel ?? 'حسب النسبة اليدوية')
                                          : (t?.allocateByAreaLabel ?? 'حسب المساحة')}
                                    </div>
                                  )}
                                  {rowRealEstateScope !== 'project' && (
                                    realEstateFloorOptions.length > 0 ? (
                                      <select
                                        data-real-estate-row={index}
                                        data-real-estate-field="floor"
                                        className={cn(
                                          "w-full min-w-0 h-9 rounded-md border px-2 py-1 text-xs focus:ring-2 focus:ring-ring",
                                          rowTargetingIssues?.floor && "border-amber-500 bg-amber-50 text-amber-900"
                                        )}
                                        value={item.realEstateFloorLabel || ''}
                                        onChange={(event) => {
                                          const value = event.target.value;
                                          const partOptions = getRealEstatePartOptions(value);
                                          setGridItems((prev) => {
                                            const next = [...prev];
                                            next[index] = {
                                              ...next[index],
                                              realEstateProjectId: watchedRealEstateProjectId || '',
                                              realEstateProjectName: selectedRealEstateProject?.name || '',
                                              realEstateFloorLabel: value,
                                              realEstatePartLabel: rowRealEstateScope === 'part' ? (partOptions[0]?.value || next[index].realEstatePartLabel || '') : '',
                                            };
                                            return next;
                                          });
                                        }}
                                      >
                                        {realEstateFloorOptions.map((floor) => (
                                          <option key={floor.id} value={floor.value}>{floor.label}</option>
                                        ))}
                                      </select>
                                    ) : (
                                      <input
                                        type="text"
                                        data-real-estate-row={index}
                                        data-real-estate-field="floor"
                                        className={cn(
                                          "w-full min-w-0 h-9 rounded-md border px-2 py-1 text-xs",
                                          rowTargetingIssues?.floor && "border-amber-500 bg-amber-50 text-amber-900"
                                        )}
                                        placeholder={t?.realEstateFloorPlaceholder ?? 'مثل: الطابق 2'}
                                        value={item.realEstateFloorLabel || ''}
                                        onChange={(event) => {
                                          const value = event.target.value;
                                          setGridItems((prev) => {
                                            const next = [...prev];
                                            next[index] = {
                                              ...next[index],
                                              realEstateProjectId: watchedRealEstateProjectId || '',
                                              realEstateProjectName: selectedRealEstateProject?.name || '',
                                              realEstateFloorLabel: value,
                                            };
                                            return next;
                                          });
                                        }}
                                      />
                                    )
                                  )}
                                  {rowRealEstateScope === 'part' && (
                                    (() => {
                                      const partOptions = getRealEstatePartOptions(item.realEstateFloorLabel);
                                      return partOptions.length > 0 ? (
                                        <select
                                          data-real-estate-row={index}
                                          data-real-estate-field="part"
                                          className={cn(
                                            "w-full min-w-0 h-9 rounded-md border px-2 py-1 text-xs focus:ring-2 focus:ring-ring",
                                            rowTargetingIssues?.part && "border-amber-500 bg-amber-50 text-amber-900"
                                          )}
                                          value={item.realEstatePartLabel || ''}
                                          onChange={(event) => {
                                            const value = event.target.value;
                                            setGridItems((prev) => {
                                              const next = [...prev];
                                              next[index] = {
                                                ...next[index],
                                                realEstateProjectId: watchedRealEstateProjectId || '',
                                                realEstateProjectName: selectedRealEstateProject?.name || '',
                                                realEstatePartLabel: value,
                                              };
                                              return next;
                                            });
                                          }}
                                        >
                                          {partOptions.map((part, partIndex) => (
                                            <option key={`${part.value}-${partIndex}`} value={part.value}>{part.label}</option>
                                          ))}
                                        </select>
                                      ) : (
                                        <input
                                          type="text"
                                          data-real-estate-row={index}
                                          data-real-estate-field="part"
                                          className={cn(
                                            "w-full min-w-0 h-9 rounded-md border px-2 py-1 text-xs",
                                            rowTargetingIssues?.part && "border-amber-500 bg-amber-50 text-amber-900"
                                          )}
                                          placeholder={t?.realEstatePartPlaceholder ?? 'مثل: الجهة الشمالية أو المحلات الأمامية'}
                                          value={item.realEstatePartLabel || ''}
                                          onChange={(event) => {
                                            const value = event.target.value;
                                            setGridItems((prev) => {
                                              const next = [...prev];
                                              next[index] = {
                                                ...next[index],
                                                realEstateProjectId: watchedRealEstateProjectId || '',
                                                realEstateProjectName: selectedRealEstateProject?.name || '',
                                                realEstatePartLabel: value,
                                              };
                                              return next;
                                            });
                                          }}
                                        />
                                      );
                                    })()
                                  )}
                                  {rowTargetingIssues && (
                                    <div className="rounded-md border border-amber-300 bg-amber-50 px-2 py-1 text-[10px] text-amber-900">
                                      {rowTargetingIssues.part
                                        ? (t?.realEstatePartRequired ?? 'يجب تحديد الطابق والجزء لهذا السطر.')
                                        : rowTargetingIssues.floor
                                          ? (t?.realEstateFloorRequired ?? 'يجب تحديد الطابق لهذا السطر.')
                                          : rowTargetingIssues.allocation
                                            ? (t?.allocationMethodRequired ?? 'يجب تحديد أساس التوزيع لهذا السطر.')
                                            : (t?.lineItemNeedsReview ?? 'هذا السطر يحتاج مراجعة قبل الحفظ.')}
                                    </div>
                                  )}
                                </div>
                              </TableCell>
                            )}
                            <TableCell className="align-middle" style={{ width: `${columnWidths.quantity}px`, minWidth: `${columnWidths.quantity}px` }}>
                              <input
                                key={`${index}-${String(item.quantity ?? '')}`}
                                type="text"
                                className={`w-full min-w-0 text-center h-10 rounded-md border px-2 py-2 ${numericNoSpinClass}`}
                                defaultValue={normalizeDecimalInput(String(item.quantity ?? ''))}
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                onBlur={e => {
                                  const rawValue = normalizeDecimalInput(e.target.value);
                                  const parsedValue = Number(rawValue);
                                  const nextQuantity = Number.isFinite(parsedValue) && parsedValue > 0 ? parsedValue : 1;

                                  setGridItems((prev) => {
                                    const currentRow = prev[index];
                                    if (!currentRow || Number(currentRow.quantity) === nextQuantity) return prev;
                                    const newItems = [...prev];
                                    newItems[index] = { ...newItems[index], quantity: nextQuantity };
                                    return newItems;
                                  });

                                  e.target.value = normalizeDecimalInput(String(nextQuantity));
                                }}
                                data-cell={`${index}-${quantityCol}`}
                                onFocus={selectAllOnFocus}
                                onMouseDown={ensureSelectOnMouseDown}
                                onKeyDown={(event) => handleInputKeyDown(event as any, index, quantityCol)}
                              />
                            </TableCell>
                            <TableCell className="align-middle" style={{ width: `${columnWidths.price}px`, minWidth: `${columnWidths.price}px` }}>
                              <input
                                type="text"
                                className={`w-full min-w-0 font-mono text-center h-10 rounded-md border px-1.5 py-2 ${numericNoSpinClass}`}
                                placeholder="السعر"
                                key={`price-${index}-${item.unitPrice ?? 0}`}
                                defaultValue={formatDecimalForInput(item.unitPrice ?? 0, 3)}
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                onBlur={(e) => {
                                  const normalizedValue = normalizeDecimalInput(e.target.value);
                                  const numericValue = Number(normalizedValue || 0);
                                  const nextPrice = Number.isFinite(numericValue) ? Number(numericValue.toFixed(3)) : 0;
                                  setGridItems((prev) => {
                                    const newItems = [...prev];
                                    if (newItems[index]) newItems[index] = { ...newItems[index], unitPrice: nextPrice };
                                    return newItems;
                                  });
                                  handleUnitPriceBlur(item.materialId, nextPrice);
                                  e.target.value = formatDecimalForInput(nextPrice, 3);
                                }}
                                onFocus={selectAllOnFocus}
                                onMouseDown={ensureSelectOnMouseDown}
                                onKeyDown={(event) => handleInputKeyDown(event as any, index, priceCol)}
                                data-cell={`${index}-${priceCol}`}
                              />
                            </TableCell>
                            {isShelfColumnVisible && typeof shelfCol === 'number' && (
                              <TableCell className="align-middle" style={{ width: `${columnWidths.shelf}px`, minWidth: `${columnWidths.shelf}px` }}>
                                <select
                                  className="w-full min-w-0 h-10 rounded-md border px-2.5 py-2 text-sm focus:ring-2 focus:ring-ring"
                                  disabled={prioritizedRowShelves.length === 0}
                                  value={item.shelfId}
                                  onMouseDown={(event) => {
                                    if (rowWarehouseId) return;
                                    event.preventDefault();
                                    toast({
                                      title: tGlobal?.error || 'تنبيه',
                                      description: t?.selectWarehouseFirst ?? 'حدد المستودع أولًا قبل اختيار الرف.',
                                      variant: 'destructive',
                                    });
                                  }}
                                  onChange={e => {
                                    if (!rowWarehouseId) {
                                      toast({
                                        title: tGlobal?.error || 'تنبيه',
                                        description: t?.selectWarehouseFirst ?? 'حدد المستودع أولًا قبل اختيار الرف.',
                                        variant: 'destructive',
                                      });
                                      return;
                                    }
                                    const newItems = [...gridItems];
                                    newItems[index].shelfId = e.target.value;
                                    setGridItems(newItems);
                                  }}
                                  data-cell={`${index}-${shelfCol}`}
                                  onKeyDown={(event) => handleGridKeyDown(event as any, index, shelfCol)}
                                >
                                  <option value="">اختر الرف</option>
                                  {prioritizedRowShelves.map((shelf) => (
                                    <option key={shelf.id} value={shelf.id}>{shelf.name}</option>
                                  ))}
                                </select>
                              </TableCell>
                            )}
                            {columnVisibility.discountPercent && typeof discountPercentCol === 'number' && (
                            <TableCell className="align-middle" style={{ width: `${columnWidths.discountPercent}px`, minWidth: `${columnWidths.discountPercent}px` }}>
                              <input
                                type="text"
                                className={`w-full min-w-0 font-mono text-center h-10 rounded-md border px-2 py-2 ${numericNoSpinClass}`}
                                key={`dpct-${index}-${item.lineDiscountPercent ?? 0}`}
                                defaultValue={normalizeDecimalInput(String(item.lineDiscountPercent ?? ''))}
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                onBlur={e => {
                                  const normalizedValue = normalizeDecimalInput(e.target.value);
                                  setGridItems((prev) => {
                                    const newItems = [...prev];
                                    if (newItems[index]) newItems[index] = { ...newItems[index], lineDiscountPercent: Number(normalizedValue || 0) };
                                    return newItems;
                                  });
                                }}
                                data-cell={`${index}-${discountPercentCol}`}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event as any, index, discountPercentCol)}
                              />
                            </TableCell>
                            )}
                            {columnVisibility.discountAmount && typeof discountAmountCol === 'number' && (
                            <TableCell className="align-middle" style={{ width: `${columnWidths.discountAmount}px`, minWidth: `${columnWidths.discountAmount}px` }}>
                              <input
                                type="text"
                                className={`font-mono w-full min-w-0 text-center h-10 rounded-md border px-2 py-2 ${numericNoSpinClass}`}
                                key={`damt-${index}-${item.lineDiscountAmount ?? 0}`}
                                defaultValue={normalizeDecimalInput(String(item.lineDiscountAmount ?? ''))}
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                onBlur={e => {
                                  const normalizedValue = normalizeDecimalInput(e.target.value);
                                  setGridItems((prev) => {
                                    const newItems = [...prev];
                                    if (newItems[index]) newItems[index] = { ...newItems[index], lineDiscountAmount: Number(normalizedValue || 0) };
                                    return newItems;
                                  });
                                }}
                                data-cell={`${index}-${discountAmountCol}`}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event as any, index, discountAmountCol)}
                              />
                            </TableCell>
                            )}
                            {columnVisibility.bonus && typeof bonusCol === 'number' && (
                            <TableCell className="align-middle" style={{ width: `${columnWidths.bonus}px`, minWidth: `${columnWidths.bonus}px` }}>
                              <input
                                type="text"
                                className={`font-mono text-green-600 w-full min-w-0 text-center h-10 rounded-md border px-2 py-2 ${numericNoSpinClass}`}
                                key={`bonus-${index}-${item.bonus ?? 0}`}
                                defaultValue={normalizeDecimalInput(String(item.bonus ?? ''))}
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                onBlur={e => {
                                  const normalizedValue = normalizeDecimalInput(e.target.value);
                                  setGridItems((prev) => {
                                    const newItems = [...prev];
                                    if (newItems[index]) newItems[index] = { ...newItems[index], bonus: Number(normalizedValue || 0) };
                                    return newItems;
                                  });
                                }}
                                data-cell={`${index}-${bonusCol}`}
                                  onFocus={selectAllOnFocus}
                                  onMouseDown={ensureSelectOnMouseDown}
                                  onKeyDown={(event) => handleInputKeyDown(event as any, index, bonusCol)}
                              />
                            </TableCell>
                            )}
                            {columnVisibility.total && typeof totalCol === 'number' && (
                            <TableCell className="text-end font-mono align-middle px-2 py-2" style={{ width: `${columnWidths.total}px`, minWidth: `${columnWidths.total}px` }}>
                              <input
                                type="text"
                                className={`font-mono w-full min-w-0 text-end h-10 rounded-md border px-2 py-2 ${numericNoSpinClass}`}
                                key={`total-${index}-${calculateLineTotal(item).toFixed(2)}`}
                                defaultValue={normalizeDecimalInput(calculateLineTotal(item).toFixed(2))}
                                lang="en"
                                dir="ltr"
                                inputMode="decimal"
                                onBlur={(e) => handleLineTotalChange(index, normalizeDecimalInput(e.target.value))}
                                data-cell={`${index}-${totalCol}`}
                                onFocus={selectAllOnFocus}
                                onMouseDown={ensureSelectOnMouseDown}
                                onKeyDown={(event) => handleInputKeyDown(event as any, index, totalCol)}
                              />
                            </TableCell>
                            )}
                            <TableCell className="align-middle">
                              <div className="flex items-center justify-center gap-1">
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="icon"
                                  title={t?.moveRowUp ?? 'نقل لأعلى (-)'}
                                  onClick={() => moveGridRow(index, index - 1)}
                                  disabled={index === 0}
                                >
                                  <span className="text-base leading-none">-</span>
                                </Button>
                                <Button
                                  type="button"
                                  variant="ghost"
                                  size="icon"
                                  title={t?.moveRowDown ?? 'نقل لأسفل (+)'}
                                  onClick={() => moveGridRow(index, index + 1)}
                                  disabled={index === gridItems.length - 1}
                                >
                                  <span className="text-base leading-none">+</span>
                                </Button>
                              <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                onClick={() => {
                                  const newItems = [...gridItems];
                                  newItems.splice(index, 1);
                                  setGridItems(newItems);
                                }}
                              >
                                <Trash2 className="h-4 w-4 text-destructive" />
                              </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                          {showItemDescriptions && description && (
                            <TableRow className={cn("bg-muted/40 transition-colors", activeGridRowIndex === index && "bg-emerald-50/80")}>
                              <TableCell colSpan={gridColSpan} className="text-xs text-muted-foreground ps-12 py-2">
                                <span>{description}</span>
                                {itemSymbolName && (
                                  <span className="ms-2 inline-block max-w-[180px] truncate align-middle">{itemSymbolName}</span>
                                )}
                              </TableCell>
                            </TableRow>
                          )}
                        </Fragment>
                      );
                    })}
                    {gridItems.length === 0 && (
                      <TableRow>
                        <TableCell
                          colSpan={gridColSpan}
                          className="text-center text-muted-foreground h-24"
                        >
                          {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
                </div>
              </div>
              <div className="mt-3 grid grid-cols-2 gap-2 md:grid-cols-5">
                <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
                  <div className="text-[11px] text-muted-foreground">{t?.itemCount ?? 'عدد الأصناف'}</div>
                  <div lang="en" dir="ltr" className="font-mono text-sm font-semibold">{itemGridSummary.itemCount}</div>
                </div>
                <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
                  <div className="text-[11px] text-muted-foreground">{t?.quantity ?? 'الكمية'}</div>
                  <div lang="en" dir="ltr" className="font-mono text-sm font-semibold">{itemGridSummary.totalQuantity.toFixed(2)}</div>
                </div>
                <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
                  <div className="text-[11px] text-muted-foreground">{t?.bonus ?? 'بونص'}</div>
                  <div lang="en" dir="ltr" className="font-mono text-sm font-semibold text-green-600">{itemGridSummary.totalBonus.toFixed(2)}</div>
                </div>
                <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
                  <div className="text-[11px] text-muted-foreground">{t?.lineDiscountAmount ?? 'إجمالي الخصم'}</div>
                  <div lang="en" dir="ltr" className="font-mono text-sm font-semibold text-amber-600">{toEnglishDigits(formatCurrency(itemGridSummary.totalLineDiscount, displayCurrencySymbol))}</div>
                </div>
                <div className="rounded-md border bg-muted/30 px-3 py-2 text-center col-span-2 md:col-span-1">
                  <div className="text-[11px] text-muted-foreground">{t?.subTotal ?? 'المجموع الفرعي'}</div>
                  <div lang="en" dir="ltr" className="font-mono text-sm font-semibold">{toEnglishDigits(formatCurrency(itemGridSummary.totalBeforeDiscount, displayCurrencySymbol))}</div>
                </div>
              </div>
              <div className="mt-4">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setPickerTargetRowIndex(null);
                    blurActiveElement();
                    setShowItemPicker(true);
                    setItemPickerQuery('');
                    setItemPickerInputResetKey((prev) => prev + 1);
                  }}
                >
                  <PlusCircle className="me-2 h-4 w-4" />{t?.addItem ?? 'إضافة صنف'}
                </Button>
              </div>
              {form.formState.errors.items?.root && (
                <p className="text-sm font-medium text-destructive mt-2">
                  {form.formState.errors.items.root.message}
                </p>
              )}
              </div>

              <Separator />

              {/* Tax Configuration Section */}
              <div dir={isRtlLayout ? 'rtl' : 'ltr'} className="rounded-md border p-4">
              
              <FormField
                control={form.control}
                name="taxMethod"
                render={({ field }) => (
                  <FormItem className="space-y-0">
                    <div className="flex flex-wrap items-center gap-x-6 gap-y-3">
                      <h3 className="text-lg font-semibold whitespace-nowrap">{t?.taxSettings ?? 'إعدادات الضريبة'}</h3>
                      <FormLabel className="mb-0 whitespace-nowrap">{t?.taxMethod ?? 'طريقة حساب الضريبة'}</FormLabel>
                      <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
                      <div className="flex items-center gap-2 whitespace-nowrap">
                        <input
                          type="radio"
                          id="tax-inclusive"
                          value="tax-inclusive"
                          checked={field.value === 'tax-inclusive'}
                          onChange={() => field.onChange('tax-inclusive')}
                          className="w-4 h-4 cursor-pointer"
                        />
                        <label htmlFor="tax-inclusive" className="cursor-pointer text-sm">
                          {t?.taxInclusive ?? 'السعر شامل الضريبة'}
                        </label>
                      </div>
                      <div className="flex items-center gap-2 whitespace-nowrap">
                        <input
                          type="radio"
                          id="invoice-level"
                          value="invoice-level"
                          checked={field.value === 'invoice-level'}
                          onChange={() => field.onChange('invoice-level')}
                          className="w-4 h-4 cursor-pointer"
                        />
                        <label htmlFor="invoice-level" className="cursor-pointer text-sm">
                          {t?.invoiceLevelTax ?? 'ضريبة على الفاتورة'}
                        </label>
                      </div>
                      <div className="flex items-center gap-2 whitespace-nowrap">
                        <input
                          type="radio"
                          id="line-level"
                          value="line-level"
                          checked={field.value === 'line-level'}
                          onChange={() => field.onChange('line-level')}
                          className="w-4 h-4 cursor-pointer"
                        />
                        <label htmlFor="line-level" className="cursor-pointer text-sm">
                          {t?.lineLevelTax ?? 'ضريبة على كل سطر'}
                        </label>
                      </div>
                      <div className="flex items-center gap-2 whitespace-nowrap">
                        <input
                          type="radio"
                          id="tax-exempt"
                          value="tax-exempt"
                          checked={field.value === 'tax-exempt'}
                          onChange={() => field.onChange('tax-exempt')}
                          className="w-4 h-4 cursor-pointer"
                        />
                        <label htmlFor="tax-exempt" className="cursor-pointer text-sm">
                          {t?.taxExempt ?? 'معفاة من الضريبة'}
                        </label>
                      </div>
                      </div>
                    </div>
                    {watchedTaxMethod === 'line-level' && (
                      <p className="text-xs text-muted-foreground mt-2">
                        {t?.lineLevelTaxHelp ?? 'سيتم حساب الضريبة لكل صنف حسب الأولويات: ضريبة الصنف > ضريبة المجموعة > الضريبة الافتراضية'}
                      </p>
                    )}
                  </FormItem>
                )}
              />

              {watchedTaxMethod === 'invoice-level' && (
                <FormField
                  control={form.control}
                  name="invoiceTaxRate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t?.taxRate ?? 'نسبة الضريبة (%)'}</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          min="0"
                          max="100"
                          placeholder="0.00"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}
                </div>
              </TabsContent>

              <TabsContent value="payment" forceMount className="space-y-4 data-[state=inactive]:hidden">
                {shipmentWorkflowEnabled && documentType === 'shipment' ? (
                  <div className="rounded-md border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
                    <span className="font-semibold">{t?.shipmentDocLabel ?? 'ارسالية'}: </span>
                    {t?.shipmentNoPaymentNote ?? 'الارسالية تؤثر على المخزون فقط ولا تتضمن قيداً محاسبياً أو مدفوعات. يمكنك إضافة المدفوعات عند ربط هذه الارسالية بفاتورة ضريبية.'}
                  </div>
                ) : (
                <div className="rounded-md border p-3">
                  <div className="mb-2">
                    <h3 className="text-sm font-semibold">{t?.paymentTabLabel ?? 'الدفع'}</h3>
                    <p className="text-[11px] text-muted-foreground">
                      {t?.paymentIntegrationHint ?? 'هذا الدفع خاص بالفاتورة الجاري إنشاؤها، وسيتم ترحيله مع حفظ الفاتورة حسب نوع الترحيل المختار.'}
                    </p>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3 mb-3">
                    <FormItem>
                      <FormLabel>{t?.paymentMethod ?? 'طريقة الدفع'}</FormLabel>
                      <Select
                        value={paymentTabMode}
                        onValueChange={(value) => setPaymentTabMode(value as PaymentTabMode)}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder={t?.paymentMethodPlaceholder ?? 'اختر طريقة الدفع'} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="cash">{t?.paymentMethodCash ?? 'نقدي'}</SelectItem>
                          <SelectItem value="check">{t?.paymentMethodCheck ?? 'شيك'}</SelectItem>
                          <SelectItem value="bank_transfer">{t?.paymentMethodBankTransfer ?? 'تحويل بنكي'}</SelectItem>
                          <SelectItem value="credit">{t?.paymentMethodCredit ?? 'ذمم (آجل)'}</SelectItem>
                          <SelectItem value="mixed">{t?.paymentMethodMixed ?? 'دفع متعدد'}</SelectItem>
                        </SelectContent>
                      </Select>
                    </FormItem>

                    {paymentTabMode === 'cash' && (
                      <FormField
                        control={form.control}
                        name="amountPaid"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>{t?.amountPaid ?? 'المدفوع'}</FormLabel>
                            <FormControl>
                              <Input type="number" min="0" step="0.01" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    )}
                  </div>

                  {(paymentTabMode === 'cash' || paymentTabMode === 'bank_transfer') && (
                    <div className="mb-4 rounded-md border p-3 space-y-3">
                      <p className="text-xs text-muted-foreground">
                        {Number(watchedAmountPaid || 0) >= grandTotal
                          ? (t?.instantPaymentHint ?? 'تم اختيار دفع فوري كامل.')
                          : Number(watchedAmountPaid || 0) > 0
                            ? (t?.partialPaymentHint ?? 'تم اختيار دفع جزئي.')
                            : (t?.noImmediatePaymentHint ?? 'لم يتم إدخال مبلغ دفع حتى الآن.')}
                      </p>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div className="md:col-span-3 rounded-md border border-dashed bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
                          {paymentTabMode === 'cash'
                            ? (t?.cashAccountAutoHint ?? 'يتم تحديد حساب الصندوق تلقائيًا من شجرة الحسابات.')
                            : (t?.bankAccountAutoHint ?? 'يتم تحديد حساب البنك تلقائيًا من شجرة الحسابات.')}
                        </div>
                      </div>
                    </div>
                  )}

                  {paymentTabMode === 'check' && (
                    <div className="mb-4 rounded-md border p-3 space-y-3">
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                        <FormItem>
                          <FormLabel>{t?.checkSource ?? 'مصدر الشيك'}</FormLabel>
                          <Select
                            value={activeSinglePaymentMethod.checkSource || 'issued'}
                            onValueChange={(value) => {
                              const selectedSource = value as 'issued' | 'incoming';
                              if (selectedSource === 'incoming') {
                                setIssuedChecks([]);
                              }
                              setPaymentMethods((prev) => {
                                const next = [...prev];
                                if (!next[0]) return prev;
                                next[0] = {
                                  ...next[0],
                                  checkSource: selectedSource,
                                  incomingCheckIds: [],
                                };
                                return next;
                              });
                            }}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder={t?.checkSourcePlaceholder ?? 'اختر مصدر الشيك'} />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="issued">{t?.issuedCheckSource ?? 'شيكات الشركة (صادرة)'}</SelectItem>
                              <SelectItem value="incoming">{t?.incomingCheckSource ?? 'شيكات واردة مجيّرة'}</SelectItem>
                            </SelectContent>
                          </Select>
                        </FormItem>
                      </div>

                      {(activeSinglePaymentMethod.checkSource || 'issued') === 'issued' && (
                        <div className="rounded-md border p-2">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead>{t?.paymentCheckNumber ?? 'رقم الشيك'} *</TableHead>
                                <TableHead>{t?.paymentBankName ?? 'اسم البنك'} *</TableHead>
                                <TableHead>{t?.paymentCheckDate ?? 'تاريخ الشيك'} *</TableHead>
                                <TableHead>{t?.amount ?? 'المبلغ'} *</TableHead>
                                <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                                <TableHead className="w-24 text-center">{t?.actions ?? 'إجراءات'}</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              <TableRow>
                                <TableCell>
                                  <Input
                                    className="h-8"
                                    placeholder={t?.paymentCheckNumberPlaceholder ?? 'مثال: CHK-001234'}
                                    defaultValue={issuedCheckDraft.checkNumber}
                                    onBlur={(e) => {
                                      const checkNumber = e.currentTarget.value;
                                      setIssuedCheckDraft((prev) => ({ ...prev, checkNumber }));
                                    }}
                                  />
                                </TableCell>
                                <TableCell>
                                  <Select
                                    value={issuedCheckDraft.bankId || undefined}
                                    onValueChange={(value) => {
                                      const bank = banks.find((b) => b.id === value);
                                      setIssuedCheckDraft((prev) => ({
                                        ...prev,
                                        bankId: value,
                                        bankName: bank?.name || '',
                                        currency: bank?.currencyCode || prev.currency || watchedCurrencyCode || defaultBaseCurrencyCode,
                                      }));
                                    }}
                                  >
                                    <SelectTrigger className="h-8 w-full">
                                      <SelectValue placeholder={t?.selectBank ?? 'اختر بنك'} />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {banks.length === 0 ? (
                                        <SelectItem value="__no_banks__" disabled>{t?.noBanksFound ?? 'لا توجد بنوك'}</SelectItem>
                                      ) : (
                                        banks.map((bank) => (
                                          <SelectItem key={bank.id} value={bank.id}>{bank.name}</SelectItem>
                                        ))
                                      )}
                                    </SelectContent>
                                  </Select>
                                </TableCell>
                                <TableCell>
                                  <Input
                                    className="h-8"
                                    type="date"
                                    defaultValue={issuedCheckDraft.checkDate || defaultRateDate}
                                    onBlur={(e) => {
                                      const checkDate = e.currentTarget.value;
                                      setIssuedCheckDraft((prev) => ({ ...prev, checkDate }));
                                    }}
                                  />
                                </TableCell>
                                <TableCell>
                                  <Input
                                    className="h-8"
                                    type="number"
                                    step="0.01"
                                    min="0"
                                    data-no-auto-select="true"
                                    defaultValue={issuedCheckDraft.amount || ""}
                                    onChange={(e) => setIssuedCheckDraft((prev) => ({
                                      ...prev,
                                      amount: e.target.value === "" ? 0 : Number(e.target.value)
                                    }))}
                                  />
                                </TableCell>
                                <TableCell>
                                  <Select
                                    value={issuedCheckDraft.currency || watchedCurrencyCode || defaultBaseCurrencyCode}
                                    disabled
                                    onValueChange={() => {}}
                                  >
                                    <SelectTrigger className="h-8 w-full">
                                      <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                      {currencies.map((currency) => (
                                        <SelectItem key={currency.code} value={currency.code}>
                                          {currency.code} - {currency.symbol}
                                        </SelectItem>
                                      ))}
                                    </SelectContent>
                                  </Select>
                                </TableCell>
                                <TableCell className="text-center">
                                  <div className="flex justify-center gap-1">
                                    <Button
                                      type="button"
                                      size="icon"
                                      className="h-8 w-8"
                                      title={t?.addCheck ?? 'إضافة شيك'}
                                      onClick={() => {
                                        if (!issuedCheckDraft.checkNumber || !issuedCheckDraft.bankId || !issuedCheckDraft.checkDate || Number(issuedCheckDraft.amount || 0) <= 0) {
                                          toast({
                                            title: tGlobal?.error || 'خطأ',
                                            description: t?.requiredCheckFields ?? 'يرجى تعبئة حقول الشيك الإلزامية.',
                                            variant: 'destructive',
                                          });
                                          return;
                                        }
                                        const nextRows = [
                                          ...issuedChecks,
                                          {
                                            ...issuedCheckDraft,
                                            id: `issued-check-${Date.now()}`,
                                            currency: issuedCheckDraft.currency || watchedCurrencyCode || defaultBaseCurrencyCode,
                                          },
                                        ];
                                        setIssuedChecks(nextRows);
                                        syncIssuedChecksToPaymentMethods(nextRows);
                                        setIssuedCheckDraft({
                                          id: 'draft',
                                          checkNumber: '',
                                          bankId: '',
                                          bankName: '',
                                          checkDate: defaultRateDate,
                                          amount: 0,
                                          currency: watchedCurrencyCode || defaultBaseCurrencyCode,
                                        });
                                      }}
                                    >
                                      <PlusCircle className="h-4 w-4" />
                                    </Button>
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="icon"
                                      className="h-8 w-8"
                                      title={t?.cancel ?? 'إلغاء'}
                                      onClick={() => {
                                        setIssuedCheckDraft({
                                          id: 'draft',
                                          checkNumber: '',
                                          bankId: '',
                                          bankName: '',
                                          checkDate: defaultRateDate,
                                          amount: 0,
                                          currency: watchedCurrencyCode || defaultBaseCurrencyCode,
                                        });
                                      }}
                                    >
                                      <X className="h-4 w-4" />
                                    </Button>
                                  </div>
                                </TableCell>
                              </TableRow>

                              {issuedChecks.map((row) => (
                                <TableRow key={row.id}>
                                  <TableCell>{row.checkNumber}</TableCell>
                                  <TableCell>{row.bankName}</TableCell>
                                  <TableCell>{row.checkDate}</TableCell>
                                  <TableCell>{formatCurrency(Number(row.amount || 0), row.currency || watchedCurrencyCode || defaultBaseCurrencyCode)}</TableCell>
                                  <TableCell>{row.currency}</TableCell>
                                  <TableCell className="text-center">
                                    <Button
                                      type="button"
                                      variant="outline"
                                      size="icon"
                                      className="h-8 w-8"
                                      onClick={() => {
                                        const nextRows = issuedChecks.filter((item) => item.id !== row.id);
                                        setIssuedChecks(nextRows);
                                        syncIssuedChecksToPaymentMethods(nextRows);
                                      }}
                                    >
                                      <Trash2 className="h-4 w-4" />
                                    </Button>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      )}

                      {(activeSinglePaymentMethod.checkSource || 'issued') === 'incoming' && (
                        <div className="rounded-md border p-3">
                          <div className="flex items-center justify-between mb-2">
                            <FormLabel className="mb-0 text-sm text-black/90">{t?.incomingChecksSelection ?? 'الشيكات الواردة للتجيير'}</FormLabel>
                            <span className="text-sm text-black/80">
                              {t?.incomingChecksTotal ?? 'الإجمالي المختار'}: {formatCurrency(singleIncomingChecksTotal, displayCurrencySymbol)}
                            </span>
                          </div>
                          <div className="rounded-md border p-2">
                            <IncomingChecksGridSelector
                              checks={availableIncomingChecks}
                              selectedIds={Array.isArray(activeSinglePaymentMethod.incomingCheckIds) ? activeSinglePaymentMethod.incomingCheckIds : []}
                              onSelectionChange={(nextIds) => {
                                setPaymentMethods((prev) => {
                                  const next = [...prev];
                                  if (!next[0]) return prev;
                                  next[0] = { ...next[0], incomingCheckIds: nextIds };
                                  return next;
                                });
                              }}
                              toCurrencyCode={watchedCurrencyCode || defaultBaseCurrencyCode}
                              convertedDisplayCurrency={displayCurrencySymbol}
                              defaultBaseCurrencyCode={defaultBaseCurrencyCode}
                              convertAmountByRates={convertAmountByRates}
                              t={t}
                            />
                          </div>
                        </div>
                      )}

                      <p className="text-xs text-muted-foreground">{t?.paymentAttachmentHint ?? 'مرفق الشيك اختياري ويمكن إضافته ضمن مرفقات الفاتورة.'}</p>
                    </div>
                  )}

                  {paymentTabMode === 'credit' && (
                    <div className="mb-4 rounded-md border border-blue-200 bg-blue-50/60 p-3 text-sm text-blue-900">
                      {t?.creditPaymentHint ?? 'سيتم تسجيلها على حساب المورد (ذمم) بدون دفع فوري.'}
                    </div>
                  )}

                  {/* Payment Methods Table */}
                  {paymentTabMode === 'mixed' && (
                  <div className="mb-4 rounded-md border p-3">
                    <div className="mb-3 flex items-center justify-between">
                      <h3 className="font-semibold text-sm">{t?.paymentMethods ?? 'الدفع المتعدد'}</h3>
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          setPaymentMethods([
                            ...paymentMethods,
                            { method: 'cash', amount: undefined, currency: watchedCurrencyCode || defaultBaseCurrencyCode },
                          ]);
                        }}
                        className="gap-1"
                      >
                        <PlusCircle className="w-4 h-4" />
                        {t?.addPaymentMethod ?? 'إضافة طريقة دفع'}
                      </Button>
                    </div>

                    {paymentMethods.length === 0 ? (
                      <p className="text-xs text-muted-foreground">{t?.noPaymentMethods ?? 'لم تتم إضافة طرق دفع بعد.'}</p>
                    ) : (
                      <div className="space-y-2">
                        <div className="grid gap-2 text-xs font-semibold text-muted-foreground">
                          <div className="grid grid-cols-4 md:grid-cols-5 gap-2">
                            <div>{t?.method ?? 'الطريقة'}</div>
                            <div>{t?.amount ?? 'المبلغ'}</div>
                            <div>{t?.currency ?? 'العملة'}</div>
                            <div className="hidden md:block">{t?.checkSource ?? 'المصدر'}</div>
                            <div className="text-right">{t?.actions ?? 'الإجراءات'}</div>
                          </div>
                        </div>
                        {paymentMethods.map((method, idx) => (
                          <Fragment key={idx}>
                          <div className="grid grid-cols-4 md:grid-cols-5 gap-2 items-center rounded border p-2 bg-muted/30">
                            <select
                              value={method.method}
                              onChange={(e) => {
                                const updated = [...paymentMethods];
                                const nextMethod = e.target.value as 'cash' | 'check' | 'bank_transfer' | 'credit';
                                updated[idx].method = nextMethod;
                                if (nextMethod === 'check') {
                                  updated[idx].checkSource = updated[idx].checkSource || 'issued';
                                } else {
                                  updated[idx].checkSource = undefined;
                                  updated[idx].incomingCheckIds = [];
                                  updated[idx].checkNumber = '';
                                  updated[idx].checkDate = '';
                                  updated[idx].bankName = '';
                                }
                                if (nextMethod === 'credit') {
                                  updated[idx].amount = 0;
                                }
                                setPaymentMethods(updated);
                              }}
                              className="rounded border px-2 py-1 text-xs"
                            >
                              <option value="cash">{t?.paymentMethodCash ?? 'نقدي'}</option>
                              <option value="check">{t?.paymentMethodCheck ?? 'شيك'}</option>
                              <option value="bank_transfer">{t?.paymentMethodBankTransfer ?? 'تحويل'}</option>
                              <option value="credit">{t?.paymentMethodCredit ?? 'آجل'}</option>
                            </select>
                            {(method.method !== 'check' && method.method !== 'credit') ? (
                              <>
                                <input
                                  data-no-auto-select="true"
                                  type="number"
                                  min="0"
                                  step="0.01"
                                  defaultValue={method.amount ?? ""}
                                  onBlur={(e) => {
                                    const updated = [...paymentMethods];
                                    const numValue = e.target.value === "" ? 0 : Number(e.target.value);
                                    updated[idx].amount = Number.isNaN(numValue) ? 0 : numValue;
                                    setPaymentMethods(updated);
                                    e.target.value = updated[idx].amount === 0 ? "" : String(updated[idx].amount);
                                  }}
                                  onKeyDown={(e) => {
                                    if (e.key === 'Enter') e.currentTarget.blur();
                                  }}
                                  className="rounded border px-2 py-1 text-xs font-mono"
                                  placeholder="0.00"
                                />
                                <select
                                  value={method.currency || defaultBaseCurrencyCode}
                                  onChange={(e) => {
                                    const updated = [...paymentMethods];
                                    updated[idx].currency = e.target.value;
                                    setPaymentMethods(updated);
                                  }}
                                  className="rounded border px-2 py-1 text-xs"
                                >
                                  {currencies.map((c) => (
                                    <option key={c.code} value={c.code}>{c.code}</option>
                                  ))}
                                </select>
                              </>
                            ) : (
                              <>
                                <div className="rounded border border-dashed px-2 py-1 text-[11px] text-muted-foreground">
                                  {method.method === 'check'
                                    ? (t?.amountInCheckDetails ?? 'المبلغ من تفاصيل الشيك')
                                    : (t?.creditNoImmediatePayment ?? 'لا يوجد مبلغ دفع فوري')}
                                </div>
                                <div className="rounded border border-dashed px-2 py-1 text-[11px] text-muted-foreground">
                                  {method.method === 'check'
                                    ? (t?.currencyInCheckDetails ?? 'العملة من البنك المختار')
                                    : (t?.creditCurrencyNotRequired ?? 'العملة غير مطلوبة')}
                                </div>
                              </>
                            )}
                            {method.method === 'check' && (
                              <div className="hidden md:block">
                                <Select
                                  value={method.checkSource || 'issued'}
                                  onValueChange={(value) => {
                                    const updated = [...paymentMethods];
                                    updated[idx].checkSource = value as 'issued' | 'incoming';
                                    updated[idx].incomingCheckIds = [];
                                    if (value === 'incoming') {
                                      updated[idx].checkNumber = '';
                                      updated[idx].checkDate = '';
                                      updated[idx].bankName = '';
                                    }
                                    setPaymentMethods(updated);
                                  }}
                                >
                                  <SelectTrigger className="h-8 w-full text-xs">
                                    <SelectValue placeholder={t?.checkSourcePlaceholder ?? 'اختر مصدر الشيك'} />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="issued">{t?.issuedCheckSource ?? 'شيكات الشركة (صادرة)'}</SelectItem>
                                    <SelectItem value="incoming">{t?.incomingCheckSource ?? 'شيكات واردة مجيّرة'}</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            )}
                            {method.method !== 'check' && <div className="hidden md:block"></div>}
                            <button
                              type="button"
                              onClick={() => {
                                setPaymentMethods(paymentMethods.filter((_, i) => i !== idx));
                              }}
                              className="text-right text-red-600 hover:text-red-700 text-xs"
                            >
                              <Trash2 className="w-4 h-4 inline" />
                            </button>
                          </div>

                          {method.method === 'credit' && (
                            <div className="rounded-md border border-blue-200 bg-blue-50/60 px-3 py-2 text-xs text-blue-900">
                              {t?.creditPaymentHint ?? 'سيتم تسجيل هذا الجزء على حساب المورد (ذمم) بدون دفع فوري.'}
                            </div>
                          )}

                          {method.method === 'check' && (method.checkSource || 'issued') === 'issued' && (
                            <div className="rounded-md border p-2 bg-background">
                              <Table>
                                <TableHeader>
                                  <TableRow>
                                    <TableHead>{t?.paymentCheckNumber ?? 'رقم الشيك'} *</TableHead>
                                    <TableHead>{t?.paymentBankName ?? 'اسم البنك'} *</TableHead>
                                    <TableHead>{t?.paymentCheckDate ?? 'تاريخ الشيك'} *</TableHead>
                                    <TableHead>{t?.amount ?? 'المبلغ'} *</TableHead>
                                    <TableHead>{t?.currency ?? 'العملة'}</TableHead>
                                  </TableRow>
                                </TableHeader>
                                <TableBody>
                                  <TableRow>
                                    <TableCell>
                                      <Input
                                        className="h-8"
                                        defaultValue={method.checkNumber || ''}
                                        placeholder={t?.paymentCheckNumberPlaceholder ?? 'مثال: CHK-001234'}
                                        onBlur={(e) => {
                                          const updated = [...paymentMethods];
                                          updated[idx].checkNumber = e.currentTarget.value;
                                          setPaymentMethods(updated);
                                        }}
                                      />
                                    </TableCell>
                                    <TableCell>
                                      <Select
                                        value={method.bankId || undefined}
                                        onValueChange={(value) => {
                                          const bank = banks.find((b) => b.id === value);
                                          const updated = [...paymentMethods];
                                          updated[idx].bankId = value;
                                          updated[idx].bankName = bank?.name || '';
                                          updated[idx].currency = bank?.currencyCode || updated[idx].currency || watchedCurrencyCode || defaultBaseCurrencyCode;
                                          setPaymentMethods(updated);
                                        }}
                                      >
                                        <SelectTrigger className="h-8 w-full">
                                          <SelectValue placeholder={t?.selectBank ?? 'اختر بنك'} />
                                        </SelectTrigger>
                                        <SelectContent>
                                          {banks.length === 0 ? (
                                            <SelectItem value="__no_banks__" disabled>{t?.noBanksFound ?? 'لا توجد بنوك'}</SelectItem>
                                          ) : (
                                            banks.map((bank) => (
                                              <SelectItem key={bank.id} value={bank.id}>{bank.name}</SelectItem>
                                            ))
                                          )}
                                        </SelectContent>
                                      </Select>
                                    </TableCell>
                                    <TableCell>
                                      <Input
                                        className="h-8"
                                        type="date"
                                        defaultValue={method.checkDate || defaultRateDate}
                                        onBlur={(e) => {
                                          const updated = [...paymentMethods];
                                          updated[idx].checkDate = e.currentTarget.value;
                                          setPaymentMethods(updated);
                                        }}
                                      />
                                    </TableCell>
                                    <TableCell>
                                      <Input
                                        className="h-8"
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        data-no-auto-select="true"
                                        defaultValue={method.amount ?? ""}
                                        onBlur={(e) => {
                                          const numValue = e.currentTarget.value === "" ? 0 : Number(e.currentTarget.value);
                                          const updated = [...paymentMethods];
                                          updated[idx].amount = Number.isNaN(numValue) ? 0 : numValue;
                                          setPaymentMethods(updated);
                                          e.currentTarget.value = updated[idx].amount === 0 ? "" : String(updated[idx].amount);
                                        }}
                                        onKeyDown={(e) => {
                                          if (e.key === 'Enter') e.currentTarget.blur();
                                        }}
                                      />
                                    </TableCell>
                                    <TableCell>
                                      <Select
                                        value={method.currency || watchedCurrencyCode || defaultBaseCurrencyCode}
                                        disabled
                                        onValueChange={() => {}}
                                      >
                                        <SelectTrigger className="h-8 w-full">
                                          <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                          {currencies.map((currency) => (
                                            <SelectItem key={currency.code} value={currency.code}>
                                              {currency.code} - {currency.symbol}
                                            </SelectItem>
                                          ))}
                                        </SelectContent>
                                      </Select>
                                    </TableCell>
                                  </TableRow>
                                </TableBody>
                              </Table>
                            </div>
                          )}

                          {method.method === 'check' && (method.checkSource || 'issued') === 'incoming' && (
                            <div className="rounded-md border p-3 bg-background">
                              <div className="flex items-center justify-between mb-2">
                                <FormLabel className="mb-0 text-sm text-black/90">{t?.incomingChecksSelection ?? 'الشيكات الواردة للتجيير'}</FormLabel>
                                <span className="text-sm text-black/80">
                                  {t?.incomingChecksTotal ?? 'الإجمالي المختار'}: {
                                    formatCurrency(
                                      availableIncomingChecks
                                        .filter((entry) => (Array.isArray(method.incomingCheckIds) ? method.incomingCheckIds : []).includes(entry.id))
                                        .reduce((sum, entry) => {
                                          const amount = Number(entry.amount || 0);
                                          const fromCurrency = entry.currency || defaultBaseCurrencyCode;
                                          const toCurrency = method.currency || watchedCurrencyCode || defaultBaseCurrencyCode;
                                          return sum + convertAmountByRates(amount, fromCurrency, toCurrency);
                                        }, 0),
                                      method.currency || watchedCurrencyCode || displayCurrencySymbol
                                    )
                                  }
                                </span>
                              </div>
                              <div className="rounded-md border p-2">
                                <IncomingChecksGridSelector
                                  checks={availableIncomingChecks}
                                  selectedIds={Array.isArray(method.incomingCheckIds) ? method.incomingCheckIds : []}
                                  onSelectionChange={(nextIds) => {
                                    const updated = [...paymentMethods];
                                    updated[idx].incomingCheckIds = nextIds;
                                    setPaymentMethods(updated);
                                  }}
                                  toCurrencyCode={method.currency || watchedCurrencyCode || defaultBaseCurrencyCode}
                                  convertedDisplayCurrency={method.currency || displayCurrencySymbol}
                                  defaultBaseCurrencyCode={defaultBaseCurrencyCode}
                                  convertAmountByRates={convertAmountByRates}
                                  t={t}
                                />
                              </div>
                            </div>
                          )}
                          </Fragment>
                        ))}
                      </div>
                    )}
                  </div>
                  )}

                </div>
                )}
              </TabsContent>

              <TabsContent value="notes" forceMount className="space-y-4 data-[state=inactive]:hidden">
                <div className="rounded-md border p-4">
                  <h3 className="text-sm font-semibold">ملاحظات</h3>
                  <p className="mt-2 text-xs text-muted-foreground">تُحفظ هذه الملاحظات مع أمر الشراء وتظهر عند فتحه لاحقًا.</p>
                  <FormField
                    control={form.control}
                    name="notes"
                    render={({ field }) => (
                      <FormItem className="mt-3">
                        <FormControl>
                          <Textarea
                            {...field}
                            rows={6}
                            placeholder={t?.orderNotesPlaceholder ?? 'اكتب أي ملاحظات داخلية على أمر الشراء...'}
                            className="resize-y"
                          />
                        </FormControl>
                        <div className="text-[11px] text-muted-foreground">
                          {(watchedNotes || '').trim().length} {t?.charactersLabel ?? 'حرف'}
                        </div>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </TabsContent>

              <TabsContent value="log" forceMount className="space-y-4 data-[state=inactive]:hidden">
                <div className="rounded-md border p-4">
                  <h3 className="text-sm font-semibold">log</h3>
                  {!existingOrder?.id ? (
                    <p className="mt-2 text-xs text-muted-foreground">سيظهر سجل العمليات بعد حفظ أمر الشراء لأول مرة.</p>
                  ) : orderActivityLog.length === 0 ? (
                    <p className="mt-2 text-xs text-muted-foreground">لا توجد عمليات مسجلة حتى الآن.</p>
                  ) : (
                    <div className="mt-3 space-y-2">
                      {orderActivityLog.map((entry) => (
                        <div key={entry.id} className="rounded-md border px-3 py-2">
                          <div className="flex flex-wrap items-center justify-between gap-2">
                            <span className="text-xs font-medium">{entry.action}</span>
                            <span className="text-[11px] text-muted-foreground">{format(new Date(entry.at), 'yyyy-MM-dd HH:mm')}</span>
                          </div>
                          <div className="mt-1 text-sm whitespace-pre-line leading-5">{formatActivityMessageForDisplay(entry.message)}</div>
                          {entry.by ? <div className="mt-1 text-[11px] text-muted-foreground">{entry.by}</div> : null}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </TabsContent>
            </Tabs>

            <div className="rounded-xl border bg-gradient-to-b from-muted/35 to-background p-3">
              <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
                <h4 className="text-sm font-semibold">{t?.invoiceSettlementSection ?? 'التسوية النهائية للفاتورة'}</h4>
                <p className="text-[11px] text-muted-foreground">
                  {t?.amountPaidLockedHint ?? 'حقل المبلغ المدفوع للعرض فقط ويتم احتسابه من تبويب الدفع.'}
                </p>
              </div>

              <div className="grid grid-cols-1 xl:grid-cols-12 gap-3 items-start">
                <div className="xl:col-span-2">
                  <FormField
                    control={form.control}
                    name="invoiceDiscountPercent"
                    render={({ field }) => (
                      <FormItem className="rounded-lg border border-sky-200 bg-background/90 p-2 space-y-1 shadow-sm">
                        <FormLabel className="text-[11px] text-muted-foreground">{t?.invoiceDiscountPercent ?? 'خصم %'}</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            type="text"
                            className="h-10 rounded-md border border-sky-200 bg-sky-50/40 px-3 text-center font-mono text-sm font-semibold shadow-none focus-visible:ring-2 focus-visible:ring-sky-300"
                            value={normalizeDecimalInput(String(field.value ?? ''))}
                            onChange={(event) => {
                              const normalizedValue = normalizeDecimalInput(event.target.value);
                              field.onChange(normalizedValue);
                            }}
                            onBlur={(event) => {
                              const normalizedValue = normalizeDecimalInput(event.target.value);
                              const clampedValue = Math.min(100, Math.max(0, Number(normalizedValue || 0)));
                              field.onChange(clampedValue.toString());
                              field.onBlur();
                            }}
                          />
                        </FormControl>
                        <FormMessage className="text-[11px]" />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="xl:col-span-2">
                  <FormField
                    control={form.control}
                    name="invoiceDiscountAmount"
                    render={({ field }) => (
                      <FormItem className="rounded-lg border border-sky-200 bg-background/90 p-2 space-y-1 shadow-sm">
                        <FormLabel className="text-[11px] text-muted-foreground">{t?.invoiceDiscountAmount ?? 'خصم'}</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            type="text"
                            className="h-10 rounded-md border border-sky-200 bg-sky-50/40 px-3 text-center font-mono text-sm font-semibold shadow-none focus-visible:ring-2 focus-visible:ring-sky-300"
                            value={normalizeDecimalInput(String(field.value ?? ''))}
                            onChange={(event) => {
                              const normalizedValue = normalizeDecimalInput(event.target.value);
                              field.onChange(normalizedValue);
                            }}
                            onBlur={(event) => {
                              const normalizedValue = normalizeDecimalInput(event.target.value);
                              const clampedValue = Math.max(0, Number(normalizedValue || 0));
                              field.onChange(clampedValue.toString());
                              field.onBlur();
                            }}
                          />
                        </FormControl>
                        <FormMessage className="text-[11px]" />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="xl:col-span-8">
                  <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-2">
                    <div className="rounded-md border bg-background/80 p-2">
                      <div className="text-[11px] text-muted-foreground">{t?.subTotal ?? 'المجموع الفرعي'}</div>
                      <div className="mt-1 font-mono text-sm">{formatCurrency(subTotal, displayCurrencySymbol)}</div>
                    </div>
                    <div className="rounded-md border bg-background/80 p-2">
                      <div className="text-[11px] text-muted-foreground">{t?.invoiceDiscountLabel ?? 'الخصم'}</div>
                      <div className="mt-1 font-mono text-sm text-green-600">-{formatCurrency(invoiceDiscount, displayCurrencySymbol)}</div>
                    </div>
                    <div className="rounded-md border bg-background/80 p-2">
                      <div className="text-[11px] text-muted-foreground">{t?.tax ?? 'الضريبة'}</div>
                      <div className="mt-1 font-mono text-sm">{formatCurrency(taxAmount, displayCurrencySymbol)}</div>
                    </div>
                    <div className="rounded-md border bg-background/80 p-2">
                      <div className="text-[11px] text-muted-foreground">{t?.grandTotal ?? 'المجموع الإجمالي'}</div>
                      <div className="mt-1 font-mono text-sm font-semibold">{formatCurrency(grandTotal, displayCurrencySymbol)}</div>
                    </div>
                    <div className="rounded-md border bg-background/80 p-2">
                      <div className="text-[11px] text-muted-foreground">{t?.amountPaid ?? 'المبلغ المدفوع'}</div>
                      <div className="mt-1 font-mono text-sm font-semibold text-emerald-600">
                        {formatCurrency(Number(watchedAmountPaid || 0), displayCurrencySymbol)}
                      </div>
                    </div>
                    <div className="rounded-md border bg-background/80 p-2">
                      <div className="text-[11px] text-muted-foreground">{t?.amountDue ?? 'المبلغ المتبقي'}</div>
                      <div className={cn('mt-1 font-mono text-sm font-semibold', amountDue > 0 ? 'text-red-600' : 'text-green-600')}>
                        {formatCurrency(amountDue, displayCurrencySymbol)}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </CardContent>

          <div className="p-6 pt-0">
            {isAcquiringEditLock ? (
              <Button type="button" disabled>
                <Loader2 className="me-2 h-4 w-4 animate-spin" />
                {t?.preparingEditLock ?? 'جاري تجهيز التعديل...'}
              </Button>
            ) : (
              <Button
                ref={submitButtonRef}
                type="submit"
                disabled={isPending || !hasEditLock}
                onClick={() => {
                  submitOriginRef.current = 'submit-button';
                }}
              >
                {isPending && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t?.saveOrder ?? 'حفظ الأمر'}
              </Button>
            )}
          </div>
        </form>
      </Form>
      </Card>

      {itemContextMenu && (
        <div
          className="fixed z-50 min-w-[180px] rounded-md border bg-background p-1 shadow-lg"
          style={{ top: itemContextMenu.y, left: itemContextMenu.x }}
          onClick={(event) => event.stopPropagation()}
        >
          <button
            type="button"
            className="w-full rounded-sm px-2.5 py-1.5 text-sm text-start hover:bg-muted"
            onClick={() => {
              setPurchasePriceDialogMaterialId(itemContextMenu.materialId);
              setShowPurchasePriceDialog(true);
              setItemContextMenu(null);
            }}
          >
            {t?.showPurchasePricesAction ?? 'عرض أسعار الشراء'}
          </button>
        </div>
      )}

      <Dialog open={showItemPicker} onOpenChange={(open) => { setShowItemPicker(open); if (!open) setPickerTargetRowIndex(null); }}>
        <DialogContent className="max-h-[85vh] overflow-y-auto w-[96vw] max-w-7xl">
          <DialogHeader>
            <DialogTitle>{t?.selectItemTitle ?? 'اختيار صنف'}</DialogTitle>
            <DialogDescription>{t?.selectItemDesc ?? 'ابحث عن الصنف ثم اضغط لإضافته للفاتورة.'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <Input
              key={itemPickerInputResetKey}
              ref={itemPickerInputRef}
              placeholder={t?.searchItemPlaceholder ?? 'ابحث عن الصنف...'}
              defaultValue={itemPickerQuery}
              onBlur={(e) => setItemPickerQuery(e.currentTarget.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  setItemPickerQuery(e.currentTarget.value);
                  (e.currentTarget as HTMLInputElement).blur();
                }
              }}
              autoFocus
            />
            <p className="text-xs text-muted-foreground">
              {normalizedItemPickerQuery
                ? `${t?.searchResultsLabel ?? 'نتائج البحث'}: ${pickerMatchedMaterials.length}`
                : `${t?.quickListHint ?? 'عرض سريع'}: ${pickerMatchedMaterials.length} ${t?.itemsLabel ?? 'صنف'}`}
            </p>
            <div className="flex justify-end">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  setShowItemPicker(false);
                  const name = String(itemPickerInputRef.current?.value ?? itemPickerQuery).trim();
                  setItemPickerQuery(name);
                  setAddMaterialInitialValues(name ? { name } : undefined);
                  blurActiveElement();
                  setShowAddMaterialDialog(true);
                }}
              >
                <PlusCircle className="me-2 h-4 w-4" />{t?.addNewItemTitle ?? 'إضافة صنف جديد'}
              </Button>
            </div>
            <div
              ref={itemPickerScrollRef}
              className="rounded-md border max-h-[420px] overflow-auto"
              onScroll={(event) => {
                setItemPickerScrollTop(event.currentTarget.scrollTop);
              }}
            >
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t?.item ?? 'الصنف'}</TableHead>
                    <TableHead>{t?.itemNumberLabel ?? 'رقم الصنف'}</TableHead>
                    <TableHead>{t?.itemSymbolNameLabel ?? 'اسم رمز الصنف'}</TableHead>
                    <TableHead>{t?.barcodeLabel ?? 'الباركود'}</TableHead>
                    <TableHead className="text-right">{t?.price ?? 'السعر'}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {pickerTopSpacerHeight > 0 && (
                    <TableRow>
                      <TableCell colSpan={5} className="p-0" style={{ height: `${pickerTopSpacerHeight}px` }} />
                    </TableRow>
                  )}
                  {filteredPickerMaterials.map((material) => (
                    <TableRow
                      key={material.id}
                      style={{ height: `${ITEM_PICKER_ROW_HEIGHT}px` }}
                      className="cursor-pointer"
                      onClick={() => {
                        const selectedMaterial = material;
                        setShowItemPicker(false);
                        setItemPickerQuery('');
                        setItemPickerInputResetKey((prev) => prev + 1);
                        setBarcodeInput('');
                        requestAnimationFrame(() => {
                          handleAddMaterialFromPicker(selectedMaterial);
                        });
                      }}
                    >
                      <TableCell className="font-medium">{material.name}</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">
                        {formatCurrency(getPreferredPurchasePrice(material), currencySymbol)}
                      </TableCell>
                    </TableRow>
                  ))}
                  {pickerBottomSpacerHeight > 0 && (
                    <TableRow>
                      <TableCell colSpan={5} className="p-0" style={{ height: `${pickerBottomSpacerHeight}px` }} />
                    </TableRow>
                  )}
                  {pickerMatchedMaterials.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center text-muted-foreground h-24">
                        {t?.noItems ?? 'لم تتم إضافة أي أصناف بعد.'}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowItemPicker(false)}>
              {t?.cancel ?? 'إلغاء'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={showPurchasePriceDialog}
        onOpenChange={(open) => {
          setShowPurchasePriceDialog(open);
          if (!open) {
            setPurchasePriceDialogMaterialId(null);
          }
        }}
      >
        <DialogContent className="max-h-[80vh] overflow-y-auto w-[96vw] max-w-6xl">
          <DialogHeader>
            <DialogTitle>
              {t?.purchasePriceHistoryTitle ?? 'سجل أسعار شراء الصنف'}
              {selectedMaterialNameForHistory ? ` - ${selectedMaterialNameForHistory}` : ''}
            </DialogTitle>
            <DialogDescription>
              {t?.purchasePriceHistoryDesc ?? 'يعرض آخر أسعار الشراء مع المورد والتاريخ وطريقة الضريبة.'}
            </DialogDescription>
          </DialogHeader>

          <div className="rounded-md border overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t?.orderNumber ?? 'رقم الفاتورة'}</TableHead>
                  <TableHead>{t?.date ?? 'التاريخ'}</TableHead>
                  <TableHead>{t?.supplier ?? 'المورد'}</TableHead>
                  <TableHead className="text-center">{t?.quantity ?? 'الكمية'}</TableHead>
                  <TableHead className="text-right">{t?.price ?? 'السعر الخام'}</TableHead>
                  <TableHead>{t?.taxMethodLabel ?? 'طريقة الضريبة'}</TableHead>
                  <TableHead className="text-center">{t?.taxRate ?? 'نسبة الضريبة'}</TableHead>
                  <TableHead className="text-right">{t?.effectivePrice ?? 'السعر المعتمد'}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {selectedMaterialPurchaseHistory.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="h-20 text-center text-muted-foreground">
                      {t?.noPurchasePriceHistory ?? 'لا توجد أسعار شراء سابقة لهذا الصنف.'}
                    </TableCell>
                  </TableRow>
                ) : (
                  selectedMaterialPurchaseHistory.map((entry, index) => (
                    <TableRow key={`${entry.orderId}-${index}`}>
                      <TableCell className="font-medium">{entry.orderNumber}</TableCell>
                      <TableCell>{entry.orderDate ? formatDateStable(entry.orderDate) : '-'}</TableCell>
                      <TableCell>{entry.supplierName}</TableCell>
                      <TableCell className="text-center font-mono">{entry.quantity.toFixed(2)}</TableCell>
                      <TableCell className="text-right font-mono">{formatCurrency(entry.rawUnitPrice, currencySymbol)}</TableCell>
                      <TableCell>{getTaxMethodLabel(entry.taxMethod)}</TableCell>
                      <TableCell className="text-center font-mono">{entry.taxRatePercent.toFixed(2)}%</TableCell>
                      <TableCell className="text-right font-mono">{formatCurrency(entry.adjustedUnitPrice, currencySymbol)}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowPurchasePriceDialog(false)}>
              {t?.close ?? tGlobal?.cancel ?? 'إغلاق'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showWeightDialog} onOpenChange={setShowWeightDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{(pendingWeightMaterial as any)?.isSized ? (t?.volumeDialogTitle ?? 'إدخال الحجم') : (t?.weightDialogTitle ?? 'قراءة الوزن')}</DialogTitle>
            <DialogDescription>
              {(pendingWeightMaterial as any)?.isSized
                ? (t?.volumeDialogDesc ?? 'أدخل حجم المنتج ليتم إضافته للأمر.')
                : (t?.weightDialogDesc ?? 'أدخل وزن المنتج ليتم إضافته للأمر.')}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">{t?.itemName ?? 'اسم الصنف'}</label>
              <Input value={pendingWeightDescription || pendingWeightMaterial?.name || ''} readOnly disabled className="bg-muted" />
            </div>
            {pendingMeasurementMode === 'volume' && pendingVolumeOptions.length > 0 && (
              <div className="space-y-2">
                <label className="text-sm font-medium">{t?.secondaryUnitLabel ?? 'الوحدة الفرعية'}</label>
                <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                  {pendingVolumeOptions.map((option) => {
                    const isActive = selectedVolumeOptionKey === option.key;
                    return (
                      <button
                        key={option.key}
                        type="button"
                        onClick={() => {
                          setSelectedVolumeOptionKey(option.key);
                          const material = pendingWeightMaterial;
                          if (!material) return;
                          setPendingWeightUnitPrice(Number(option.price || 0));
                          setPendingWeightDescription(`${material.name} - ${option.label}`);
                        }}
                        className={`rounded-md border px-3 py-2 text-sm text-right transition-colors ${isActive ? 'border-primary bg-primary/10 text-primary' : 'border-input hover:bg-muted/60'}`}
                      >
                        <div className="font-medium">{option.label}</div>
                        <div className="text-xs text-muted-foreground">{t?.salePriceLabel ?? 'السعر'}: {Number(option.price || 0).toFixed(2)}</div>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
            {pendingMeasurementMode !== 'volume' && (
              <div className="space-y-2">
                <label className="text-sm font-medium">{t?.weightLabel ?? 'الوزن (كغم)'}</label>
                <Input
                  type="number"
                  step="0.001"
                  value={weightInput}
                  onChange={(e) => setWeightInput(e.target.value)}
                  placeholder={t?.weightPlaceholder ?? 'أدخل الوزن...'}
                />
              </div>
            )}
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setShowWeightDialog(false)}>
              {tGlobal?.cancel ?? 'إلغاء'}
            </Button>
            <Button
              type="button"
              onClick={() => {
                const isVolumeMode = pendingMeasurementMode === 'volume';
                const weightValue = isVolumeMode ? 1 : parseFloat(weightInput);
                if (!pendingWeightMaterial || (!isVolumeMode && (isNaN(weightValue) || weightValue <= 0))) {
                  toast({
                    title: t?.validationError ?? 'خطأ في التحقق',
                    description: (pendingWeightMaterial as any)?.isSized
                      ? (t?.volumeInvalid ?? 'الرجاء إدخال حجم صحيح.')
                      : (t?.weightInvalid ?? 'الرجاء إدخال وزن صحيح.'),
                    variant: 'destructive',
                  });
                  return;
                }

                const { updatedQuantity } = addOrIncrementItem(
                  pendingWeightMaterial.id,
                  pendingWeightUnitPrice,
                  weightValue
                );

                toast({
                  title: t?.itemAdded ?? 'تمت إضافة الصنف',
                  description: `${pendingWeightDescription || pendingWeightMaterial.name}: ${updatedQuantity}`,
                });

                setShowWeightDialog(false);
                setPendingWeightMaterial(null);
                setPendingWeightUnitPrice(0);
                setPendingWeightDescription('');
                setPendingMeasurementMode('weight');
                setPendingVolumeOptions([]);
                setSelectedVolumeOptionKey('');
                setWeightInput('');
              }}
            >
              {tGlobal?.submit ?? 'إضافة'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Dialog
        open={showStockReportDialog}
        onOpenChange={(open) => {
          setShowStockReportDialog(open);
          if (!open) {
            setStockReport(null);
          }
        }}
      >
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{t?.stockReportTitle ?? 'تقرير محتوى الأرفف'}</DialogTitle>
            <DialogDescription>
              {t?.stockReportDescription ?? 'الرصيد الحالي للصنف حسب المستودع والرف بعد حفظ الفاتورة.'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {(stockReport || []).length === 0 && (
              <p className="text-sm text-muted-foreground">
                {t?.noStockReport ?? 'لا توجد بيانات رصيد لعرضها.'}
              </p>
            )}
            {(stockReport || []).map((entry) => {
              const material = materials.find((m) => m.id === entry.materialId);
              return (
                <div key={entry.materialId} className="rounded-md border p-3">
                  <div className="font-medium">
                    {material?.name || entry.materialId}
                  </div>
                  {entry.locations.length === 0 ? (
                    <p className="text-sm text-muted-foreground mt-2">
                      {t?.noStockLocations ?? 'لا يوجد رصيد مسجل لهذا الصنف على الأرفف.'}
                    </p>
                  ) : (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>{t?.warehouseLabel ?? 'المستودع'}</TableHead>
                          <TableHead>{t?.shelfLabel ?? 'الرف'}</TableHead>
                          <TableHead className="text-right">{t?.quantityLabel ?? 'الكمية'}</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {entry.locations.map((loc) => (
                          <TableRow
                            key={`${entry.materialId}-${loc.warehouseId || loc.warehouseName}-${loc.shelfId || loc.shelfName}`}
                          >
                            <TableCell>{loc.warehouseName}</TableCell>
                            <TableCell>{loc.shelfName}</TableCell>
                            <TableCell className="text-right font-mono">{loc.quantity}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  )}
                </div>
              );
            })}
          </div>
          <DialogFooter>
            <Button type="button" onClick={() => setShowStockReportDialog(false)}>
              {tGlobal?.close ?? 'إغلاق'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <div className="fixed inset-0 pointer-events-none" style={{ zIndex: 999 }}>
        <Dialog open={aiInvoiceEntryEnabled && aiExtractionDialogOpen} onOpenChange={setAiExtractionDialogOpen}>
          <DialogContent className="pointer-events-auto">
            <DialogHeader>
              <DialogTitle>{'التحليل الذكي للفاتورة'}</DialogTitle>
              <DialogDescription>
                {'اختر طريقة الإدخال: تحميل صورة فاتورة أو إدخال البيانات عبر النص/الصوت'}
              </DialogDescription>
            </DialogHeader>

          <div className="space-y-4">
            {/* Mode Selection */}
            <div className="flex gap-3 mb-4">
              <button
                type="button"
                onClick={() => {
                  setAiExtractionMode('image');
                  setAiExtractionVoiceText('');
                }}
                className={cn(
                  'flex-1 rounded-lg border-2 p-4 text-center transition-all cursor-pointer',
                  aiExtractionMode === 'image'
                    ? 'border-primary bg-primary/5'
                    : 'border-muted hover:border-muted-foreground/30 bg-muted/20'
                )}
              >
                <div className="text-2xl mb-2">📸</div>
                <div className="font-medium text-sm">{'تحليل الصورة'}</div>
                <div className="text-xs text-muted-foreground">{'رفع صورة الفاتورة'}</div>
              </button>

              <button
                type="button"
                onClick={() => {
                  setAiExtractionMode('voice');
                  setAiExtractionDocument(null);
                }}
                className={cn(
                  'flex-1 rounded-lg border-2 p-4 text-center transition-all cursor-pointer',
                  aiExtractionMode === 'voice'
                    ? 'border-primary bg-primary/5'
                    : 'border-muted hover:border-muted-foreground/30 bg-muted/20'
                )}
              >
                <div className="text-2xl mb-2">🎤</div>
                <div className="font-medium text-sm">{'إدخال نصي'}</div>
                <div className="text-xs text-muted-foreground">{'إدخال البيانات نصياً'}</div>
              </button>
            </div>

            {/* Image Mode */}
            {aiExtractionMode === 'image' && (
              <div className="space-y-3">
                <div className="text-sm font-medium">{'الوثائق المرفقة'}</div>
                {orderDocuments.length === 0 ? (
                  <div className="space-y-3 text-center py-4">
                    <p className="text-sm text-muted-foreground">
                      {'لا توجد وثائق مرفقة. يرجى رفع صورة الفاتورة أولاً.'}
                    </p>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={handlePickDocuments}
                      disabled={isUploadingDocument}
                      className="mx-auto"
                    >
                      <Paperclip className="me-2 h-4 w-4" />
                      {isUploadingDocument ? 'جارٍ الرفع...' : '📤 رفع صورة الفاتورة'}
                    </Button>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-3">
                      {orderDocuments.map((doc) => (
                        <button
                          key={doc.id}
                          type="button"
                          onClick={() => setAiExtractionDocument(doc)}
                          className={cn(
                            'w-full text-left p-3 rounded-lg border-2 transition-all text-sm',
                            aiExtractionDocument?.id === doc.id
                              ? 'border-primary bg-primary/5'
                              : 'border-muted hover:border-muted-foreground/30'
                          )}
                        >
                          <div className="flex items-center gap-2">
                            <FileText className="h-4 w-4" />
                            <span className="truncate">{doc.name}</span>
                          </div>
                        </button>
                      ))}
                    </div>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={handlePickDocuments}
                      disabled={isUploadingDocument}
                      className="w-full"
                    >
                      <Paperclip className="me-2 h-4 w-4" />
                      {isUploadingDocument ? 'جارٍ الرفع...' : '📤 رفع وثائق إضافية'}
                    </Button>
                  </div>
                )}
              </div>
            )}

            {/* Voice/Text Mode */}
            {aiExtractionMode === 'voice' && (
              <div className="space-y-3">
                <div className="text-sm font-medium">{'أدخل بيانات الفاتورة'}</div>
                <Textarea
                  placeholder="مثال: المورد: أحمد للتوريدات، رقم الفاتورة: 123، تاريخ الفاتورة: 2024-01-15، أصناف: كيس رز 50 كجم بسعر 450 ريال، كمية 5، مجموع الفاتورة: 2250 ريال"
                  value={aiExtractionVoiceText}
                  onChange={(e) => setAiExtractionVoiceText(e.target.value)}
                  className="min-h-32 resize-none"
                />
              </div>
            )}
          </div>

          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => setAiExtractionDialogOpen(false)}
            >
              {'إلغاء'}
            </Button>
            <Button
              type="button"
              disabled={
                isAiExtracting ||
                (aiExtractionMode === 'image' && !aiExtractionDocument) ||
                (aiExtractionMode === 'voice' && !aiExtractionVoiceText.trim())
              }
              onClick={handleAiExtraction}
            >
              {isAiExtracting ? (
                <>
                  <Loader2 className="me-2 h-4 w-4 animate-spin" />
                  {'جارٍ التحليل...'}
                </>
              ) : (
                '🚀 ابدأ التحليل'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      </div>

      {/* AI Review Dialog - Step 2: Review Extracted Data */}
      <div className="fixed inset-0 pointer-events-none" style={{ zIndex: 998 }}>
        <Dialog open={aiInvoiceEntryEnabled && aiReviewDialogOpen} onOpenChange={setAiReviewDialogOpen}>
          <DialogContent className="pointer-events-auto">
            <DialogHeader>
              <DialogTitle>{'مراجعة البيانات المستخرجة'}</DialogTitle>
              <DialogDescription>
                {`ثقة التحليل: ${(aiExtractionConfidence * 100).toFixed(0)}% - يرجى المراجعة والتعديل قبل التطبيق`}
              </DialogDescription>
          </DialogHeader>

          {aiExtractionResult && (
            <div className="space-y-4">
              {/* Supplier */}
              <div className="space-y-2 rounded-lg border p-3">
                <div className="font-medium text-sm">{'المورد'}</div>
                <Input
                  value={aiExtractionResult.supplierName || ''}
                  readOnly
                  className="text-sm bg-muted/50"
                />
              </div>

              {/* Invoice Details */}
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2 rounded-lg border p-3">
                  <div className="font-medium text-sm">{'رقم الفاتورة'}</div>
                  <Input
                    value={aiExtractionResult.invoiceNumber || ''}
                    readOnly
                    className="text-sm bg-muted/50"
                  />
                </div>
                <div className="space-y-2 rounded-lg border p-3">
                  <div className="font-medium text-sm">{'تاريخ الفاتورة'}</div>
                  <Input
                    value={aiExtractionResult.invoiceDate || ''}
                    readOnly
                    className="text-sm bg-muted/50"
                  />
                </div>
              </div>

              {/* Items Table */}
              <div className="space-y-2 rounded-lg border p-3">
                <div className="font-medium text-sm mb-3">{'الأصناف'}</div>
                <div className="overflow-x-auto">
                  <Table className="text-sm">
                    <TableHeader>
                      <TableRow>
                        <TableHead>{'الصنف'}</TableHead>
                        <TableHead className="text-right">{'الكمية'}</TableHead>
                        <TableHead className="text-right">{'سعر الوحدة'}</TableHead>
                        <TableHead className="text-right">{'الإجمالي'}</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {(aiExtractionResult.items || []).map((item: any, idx: number) => (
                        <TableRow key={idx}>
                          <TableCell>{item.name}</TableCell>
                          <TableCell lang="en" dir="ltr" className="text-right font-mono">{item.quantity}</TableCell>
                          <TableCell lang="en" dir="ltr" className="text-right font-mono">{item.unitPrice}</TableCell>
                          <TableCell lang="en" dir="ltr" className="text-right font-mono">{item.total}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </div>

              {/* Totals */}
              <div className="grid grid-cols-3 gap-3">
                <div className="space-y-2 rounded-lg border border-emerald-200 bg-emerald-50/50 p-3">
                  <div className="font-medium text-sm text-emerald-900">{'المجموع'}</div>
                  <div lang="en" dir="ltr" className="text-lg font-bold font-mono text-emerald-700">
                    {Number(aiExtractionResult.invoiceTotal || 0).toFixed(2)}
                  </div>
                </div>
                {aiExtractionResult.taxRate && (
                  <div className="space-y-2 rounded-lg border border-amber-200 bg-amber-50/50 p-3">
                    <div className="font-medium text-sm text-amber-900">{'نسبة الضريبة'}</div>
                    <div lang="en" dir="ltr" className="text-lg font-bold font-mono text-amber-700">
                      {(Number(aiExtractionResult.taxRate || 0) * 100).toFixed(1)}%
                    </div>
                  </div>
                )}
                {aiExtractionResult.taxAmount && (
                  <div className="space-y-2 rounded-lg border border-blue-200 bg-blue-50/50 p-3">
                    <div className="font-medium text-sm text-blue-900">{'الضريبة'}</div>
                    <div lang="en" dir="ltr" className="text-lg font-bold font-mono text-blue-700">
                      {Number(aiExtractionResult.taxAmount || 0).toFixed(2)}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setAiReviewDialogOpen(false);
                setAiExtractionResult(null);
              }}
            >
              {'الرجوع'}
            </Button>
            <Button
              type="button"
              disabled={!aiExtractionResult}
              onClick={handleApplyAiExtraction}
            >
              {'✅ تطبيق البيانات'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      </div>
    </div>
  );
}
