'use client';

import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import TransferShortageResolutionDialog, { MissingCostItem, ShortageBreakdownRow } from '@/components/shared/transfer-shortage-resolution-dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import { handleAcquireTransferLock, handleCancelInternalTransferDocument, handleCreateInternalTransferDocument, handleGetPurchaseOrderCloneQuantities, handleReleaseTransferLock, handleUpdateInternalTransferDocument, handleResolveInternalTransferShortage } from '@/lib/actions';
import type { InternalTransferDocument, InternalTransferItem, ProductionItem, StockLocationBalance, Warehouse } from '@/lib/types';
import { format, parseISO } from 'date-fns';
import { Eye, Loader2, Pencil, PlusCircle, Trash2 } from 'lucide-react';
import Link from 'next/link';

export type TransferDocumentRow = InternalTransferDocument & {
  itemCount: number;
  totalQty: number;
  receivedQty: number;
  effectiveReceiptStatus: 'pending' | 'partial' | 'received' | 'pending-approval';
};

type Props = {
  documents: InternalTransferDocument[];
  materials: ProductionItem[];
  warehouses: Warehouse[];
  stockLocationsByMaterial: Record<string, StockLocationBalance[]>;
  allowedWarehouseIds?: string[] | null;
  focusDocId?: string;
  cloneFromDocId?: string;
  createFromPurchaseOrderId?: string;
  autoOpenCreate?: boolean;
  /** When set, renders the edit form inline on a dedicated page instead of a dialog */
  inlineEditDocId?: string;
};

function formatDate(value: string | Date) {
  try {
    const iso = value instanceof Date ? value.toISOString() : value;
    return format(parseISO(iso), 'yyyy-MM-dd');
  } catch {
    return typeof value === 'string' ? value : '';
  }
}

function formatSourcePurchaseDocumentType(value?: 'shipment' | 'tax_invoice') {
  if (value === 'shipment') return 'ارسالية';
  if (value === 'tax_invoice') return 'فاتورة ضريبية';
  return '-';
}

function getMaterialDisplayName(material: ProductionItem) {
  return material.itemNumber ? `${material.itemNumber} - ${material.name}` : material.name;
}

function clamp(value: number, min = 80, max = 500) {
  return Math.min(Math.max(value, min), max);
}

function isAutoShelfDistributionDoc(doc: InternalTransferDocument) {
  const note = String(doc.note || '').toLowerCase();
  return note.includes('shelf distribution for purchase order') && !note.includes('إعادة إنشاء');
}

function shouldTreatAsAutoReceived(doc: InternalTransferDocument) {
  if (!isAutoShelfDistributionDoc(doc)) return false;
  const receiptStatus = doc.receiptStatus ?? 'pending';
  if (receiptStatus !== 'pending') return false;
  if (!Array.isArray(doc.items) || doc.items.length === 0) return false;

  return doc.items.every((item) => {
    const quantity = Number(item.quantity || 0);
    const received = Number(item.receivedQuantity || 0);
    return quantity > 0 && received <= 0;
  });
}

function buildRecreateNote(sourceNote: string | undefined, sourceTransferNumber: string) {
  const suffix = '(إعادة إنشاء بعد الإلغاء)';
  const cleaned = String(sourceNote || '')
    .replace(/\s*\(إعادة إنشاء بعد الإلغاء\)\s*/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();
  const base = cleaned || `إعادة إنشاء من ${sourceTransferNumber}`;
  return `${base} ${suffix}`.trim();
}

export default function InternalTransferDocuments({ documents, materials, warehouses, stockLocationsByMaterial, allowedWarehouseIds, focusDocId, cloneFromDocId, createFromPurchaseOrderId, autoOpenCreate, inlineEditDocId }: Props) {
  const { toast } = useToast();
  const router = useRouter();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editDoc, setEditDoc] = useState<InternalTransferDocument | null>(null);
  const [isSaving, startSaveTransition] = useTransition();
  const [isCancelling, startCancelTransition] = useTransition();
  const [isLockPending, startLockTransition] = useTransition();
  const [isResolving, startResolveTransition] = useTransition();
  const [lockedMaterialIds, setLockedMaterialIds] = useState<Set<string>>(new Set());
  const [barcodeInput, setBarcodeInput] = useState('');
  const [materialPickerOpen, setMaterialPickerOpen] = useState(false);
  const [materialSearch, setMaterialSearch] = useState('');
  const [resolveDoc, setResolveDoc] = useState<InternalTransferDocument | null>(null);
  const [resolutionType, setResolutionType] = useState<'supplier' | 'employee' | 'wastage' | 'resend'>('supplier');
  const [resolutionNote, setResolutionNote] = useState('');
  const [resolutionMissingCostItems, setResolutionMissingCostItems] = useState<MissingCostItem[]>([]);
  const [insufficientStockHint, setInsufficientStockHint] = useState<{
    materialId: string;
    fromWarehouseId?: string;
    fromShelfId?: string;
    requested?: number;
    available: number;
  } | null>(null);
  const [activeTab, setActiveTab] = useState<'all' | 'stuck'>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'cancelled'>('all');
  const [receiptFilter, setReceiptFilter] = useState<'all' | 'pending' | 'partial' | 'received' | 'pending-approval'>('all');
  const [createdByFilter, setCreatedByFilter] = useState('all');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');

  const [formState, setFormState] = useState({
    date: new Date().toISOString().slice(0, 10),
    enableWarehouseTransfer: true,
    enableShelfTransfer: true,
    allowZeroItems: false,
    note: '',
  });
  const [transferMeta, setTransferMeta] = useState<{
    supplierId?: string;
    supplierName?: string;
    supplierInvoiceNumber?: string;
    sourcePurchaseOrderId?: string;
    sourcePurchaseOrderNumber?: string;
    sourcePurchaseDocumentType?: 'shipment' | 'tax_invoice';
  }>({});

  const [items, setItems] = useState<Array<InternalTransferItem & { rowId: string }>>([]);
  const rowIdRef = useRef(0);
  const cloneHandledRef = useRef<string | null>(null);
  const createFromPurchaseOrderHandledRef = useRef<string | null>(null);
  const createHandledRef = useRef(false);
  const [columnWidths, setColumnWidths] = useState<number[]>([260, 120, 150, 150, 80]);
  const resizingRef = useRef<{ index: number; startX: number; startWidth: number } | null>(null);

  const materialById = useMemo(() => new Map(materials.map((m) => [m.id, m])), [materials]);
  const warehouseById = useMemo(() => new Map(warehouses.map((w) => [w.id, w])), [warehouses]);
  const isWarehouseAllowed = useCallback(
    (warehouseId: string) => {
      if (!allowedWarehouseIds || allowedWarehouseIds.length === 0) return true;
      return allowedWarehouseIds.includes(warehouseId);
    },
    [allowedWarehouseIds]
  );

  const filteredMaterials = useMemo(() => materials, [materials]);

  const searchedMaterials = useMemo(() => {
    if (!materialSearch.trim()) return materials;
    const search = materialSearch.toLowerCase().trim();
    
    // دالة مساعدة للبحث الذكي
    const smartSearch = (text: string): boolean => {
      if (!text) return false;
      const lowerText = text.toLowerCase();
      
      // البحث المباشر
      if (lowerText.includes(search)) return true;
      
      // البحث بالأحرف الأولى من كل كلمة
      const words = lowerText.split(/\s+/);
      const searchWords = search.split(/\s+/);
      
      // التحقق من أن كل كلمة بحث موجودة في إحدى الكلمات
      return searchWords.every(searchWord =>
        words.some(word => word.includes(searchWord))
      );
    };
    
    return materials.filter((m) =>
      smartSearch(m.name) ||
      smartSearch(m.itemNumber || '') ||
      smartSearch(m.barcode || '') ||
      smartSearch(m.secondaryBarcode || '') ||
      (m.additionalBarcodes?.some(bc => smartSearch(bc)) ?? false)
    );
  }, [materials, materialSearch]);

  const rows = useMemo<TransferDocumentRow[]>(
    () => documents.map((doc) => {
      const autoReceived = shouldTreatAsAutoReceived(doc);
      return {
        ...doc,
        effectiveReceiptStatus: autoReceived ? 'received' : (doc.receiptStatus ?? 'pending'),
        itemCount: doc.items.length,
        totalQty: doc.items.reduce((sum, item) => sum + Number(item.quantity || 0), 0),
        receivedQty: autoReceived
          ? doc.items.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
          : doc.items.reduce((sum, item) => sum + Number(item.receivedQuantity ?? 0), 0),
      };
    }),
    [documents]
  );

  const isStuckDocument = useCallback((doc: TransferDocumentRow) => {
    const receiptStatus = doc.effectiveReceiptStatus;
    const hasShortage = doc.receivedQty < doc.totalQty || (doc.note || '').includes('نقص');
    return doc.status === 'active' && (receiptStatus === 'pending' || receiptStatus === 'partial' || receiptStatus === 'pending-approval' || hasShortage);
  }, []);

  const uniqueCreators = useMemo(
    () => Array.from(new Set(rows.map((doc) => doc.createdBy || '').filter(Boolean))).sort((a, b) => a.localeCompare(b, 'ar')),
    [rows]
  );

  const filteredRows = useMemo(() => {
    return rows.filter((doc) => {
      if (activeTab === 'stuck' && !isStuckDocument(doc)) return false;
      if (statusFilter !== 'all' && doc.status !== statusFilter) return false;

      const normalizedReceipt = doc.effectiveReceiptStatus;
      if (receiptFilter !== 'all' && normalizedReceipt !== receiptFilter) return false;

      if (createdByFilter !== 'all' && (doc.createdBy || '') !== createdByFilter) return false;

      const docDate = formatDate(doc.date);
      if (dateFrom && docDate < dateFrom) return false;
      if (dateTo && docDate > dateTo) return false;

      if (searchQuery.trim()) {
        const q = searchQuery.trim().toLowerCase();
        const haystack = [
          doc.transferNumber,
          doc.note,
          doc.createdBy,
          doc.supplierName,
          doc.sourcePurchaseOrderNumber,
          doc.supplierInvoiceNumber,
          doc.sourcePurchaseDocumentType,
        ]
          .map((value) => String(value || '').toLowerCase())
          .join(' ');
        if (!haystack.includes(q)) return false;
      }

      return true;
    });
  }, [activeTab, createdByFilter, dateFrom, dateTo, isStuckDocument, receiptFilter, rows, searchQuery, statusFilter]);

  const stuckCount = useMemo(() => rows.filter((doc) => isStuckDocument(doc)).length, [rows, isStuckDocument]);

  const focusedDoc = useMemo(
    () => (focusDocId ? documents.find((doc) => doc.id === focusDocId) || null : null),
    [documents, focusDocId]
  );

  const focusedLinkedActiveDocs = useMemo(() => {
    if (!focusedDoc) return [] as InternalTransferDocument[];
    return documents.filter((doc) => {
      if (doc.id === focusedDoc.id) return false;
      if (doc.status === 'cancelled') return false;
      return String(doc.note || '').includes(focusedDoc.transferNumber);
    });
  }, [documents, focusedDoc]);

  const focusedFollowupActions = useMemo(() => {
    if (!focusedDoc) return [] as Array<{ label: string; details: string; href?: string; transferNumber?: string; previewHref?: string }>;

    const actions: Array<{ label: string; details: string; href?: string; transferNumber?: string; previewHref?: string }> = [];
    const receiptStatus = focusedDoc.receiptStatus ?? 'pending';

    if (receiptStatus !== 'pending') {
      const receiptLabel = receiptStatus === 'received'
        ? 'تم استلام السند بالكامل'
        : receiptStatus === 'partial'
          ? 'تم استلام جزئي للسند'
          : receiptStatus === 'pending-approval'
            ? 'يوجد زيادة بانتظار الاعتماد'
            : `تم تحديث حالة الاستلام إلى ${receiptStatus}`;

      actions.push({
        label: 'إجراء استلام',
        details: receiptLabel,
        href: `/admin/data/internal-transfers/${encodeURIComponent(focusedDoc.id)}`,
        transferNumber: focusedDoc.transferNumber,
        previewHref: `/admin/data/internal-transfers/${encodeURIComponent(focusedDoc.id)}`,
      });
    }

    if (focusedDoc.shortageResolutionType || focusedDoc.shortageResolvedAt || focusedDoc.shortageJournalEntryId) {
      const resolutionLabel = focusedDoc.shortageResolutionType === 'supplier'
        ? 'تمت معالجة النقص على المورد'
        : focusedDoc.shortageResolutionType === 'employee'
          ? 'تمت معالجة النقص على الموظف'
          : focusedDoc.shortageResolutionType === 'wastage'
            ? 'تمت معالجة النقص كهالك'
            : focusedDoc.shortageResolutionType === 'resend'
              ? 'تمت إعادة إرسال النقص'
              : 'تمت معالجة النقص';

      actions.push({
        label: 'معالجة نقص',
        details: resolutionLabel,
        href: focusedDoc.shortageJournalEntryId
          ? `/admin/accounting/entries?entryId=${encodeURIComponent(focusedDoc.shortageJournalEntryId)}`
          : `/admin/data/internal-transfers/${encodeURIComponent(focusedDoc.id)}`,
        transferNumber: focusedDoc.transferNumber,
        previewHref: `/admin/data/internal-transfers/${encodeURIComponent(focusedDoc.id)}`,
      });
    }

    focusedLinkedActiveDocs.forEach((doc) => {
      actions.push({
        label: 'سند لاحق مرتبط',
        details: `${doc.transferNumber} (${doc.status === 'cancelled' ? 'ملغي' : 'نشط'})`,
        href: `/admin/data/internal-transfers/${encodeURIComponent(doc.id)}`,
        transferNumber: doc.transferNumber,
        previewHref: `/admin/data/internal-transfers/${encodeURIComponent(doc.id)}`,
      });
    });

    return actions;
  }, [focusedDoc, focusedLinkedActiveDocs]);

  const focusedHasFollowupAction = useMemo(() => {
    if (!focusedDoc) return false;
    if (focusedLinkedActiveDocs.length > 0) return true;
    return false;
  }, [focusedDoc, focusedLinkedActiveDocs]);

  const getWarehouseName = useCallback(
    (id: string) => warehouseById.get(id)?.name || id,
    [warehouseById]
  );

  const releaseAllLocks = useCallback(async () => {
    if (lockedMaterialIds.size === 0) return;
    const ids = Array.from(lockedMaterialIds);
    setLockedMaterialIds(new Set());
    await Promise.all(ids.map((materialId) => handleReleaseTransferLock({ materialId })));
  }, [lockedMaterialIds]);

  const defaultWarehouseId = warehouses[0]?.id || '';
  const defaultShelfId = warehouses[0]?.shelves?.[0]?.id || '';
  const [warehouseSelection, setWarehouseSelection] = useState(() => ({
    fromWarehouseId: defaultWarehouseId,
    toWarehouseId: defaultWarehouseId,
  }));

  const getFirstShelfId = useCallback(
    (warehouseId: string) => warehouseById.get(warehouseId)?.shelves?.[0]?.id || '',
    [warehouseById]
  );

  const getDefaultShelfId = useCallback(
    (warehouseId: string) => getFirstShelfId(warehouseId) || defaultShelfId,
    [getFirstShelfId, defaultShelfId]
  );

  const getShortageBreakdown = useCallback(
    (doc: InternalTransferDocument): ShortageBreakdownRow[] => {
      return doc.items
        .map((item) => {
          const material = materialById.get(item.materialId);
          const snapshotUnitCost = Number(item.unitCostSnapshot || 0);
          const liveUnitCost = Number(material?.purchasePrice ?? material?.salePrice ?? 0) || 0;
          const unitCost = snapshotUnitCost > 0 ? snapshotUnitCost : liveUnitCost;
          const shortageQty = Number((item.rejectedQuantity ?? (item.receivedQuantity === undefined
            ? item.quantity
            : Math.max(0, item.quantity - (item.receivedQuantity || 0)))) || 0);
          const materialName = material ? getMaterialDisplayName(material) : item.materialId;
          return {
            materialId: item.materialId,
            materialName,
            shortageQty,
            unitCost,
            totalCost: shortageQty * unitCost,
          };
        })
        .filter((row) => row.shortageQty > 0);
    },
    [materialById]
  );

  const resolveShortageRows = useMemo(
    () => (resolveDoc ? getShortageBreakdown(resolveDoc) : []),
    [resolveDoc, getShortageBreakdown]
  );

  const resolveShortageTotal = useMemo(
    () => resolveShortageRows.reduce((sum, row) => sum + row.totalCost, 0),
    [resolveShortageRows]
  );

  const hasZeroCostShortageRows = useMemo(
    () => resolveShortageRows.some((row) => row.unitCost <= 0),
    [resolveShortageRows]
  );

  useEffect(() => {
    if (!formState.enableWarehouseTransfer) return;
    setItems((prev) =>
      prev.map((item) => {
        const nextFromShelfId = isWarehouseAllowed(item.fromWarehouseId)
          ? item.fromShelfId
          : getDefaultShelfId(item.fromWarehouseId) || item.fromShelfId;
        const nextToShelfId = isWarehouseAllowed(item.toWarehouseId)
          ? item.toShelfId
          : getDefaultShelfId(item.toWarehouseId) || item.toShelfId;
        if (nextFromShelfId === item.fromShelfId && nextToShelfId === item.toShelfId) {
          return item;
        }
        return {
          ...item,
          fromShelfId: nextFromShelfId,
          toShelfId: nextToShelfId,
        };
      })
    );
  }, [formState.enableWarehouseTransfer, getDefaultShelfId, isWarehouseAllowed]);

  useEffect(() => {
    if (!warehouseSelection.fromWarehouseId && defaultWarehouseId) {
      setWarehouseSelection({ fromWarehouseId: defaultWarehouseId, toWarehouseId: defaultWarehouseId });
    }
  }, [defaultWarehouseId, warehouseSelection.fromWarehouseId]);

  useEffect(() => {
    const handleMouseMove = (event: MouseEvent) => {
      if (!resizingRef.current) return;
      const { index, startX, startWidth } = resizingRef.current;
      const delta = event.clientX - startX;
      setColumnWidths((prev) => prev.map((width, i) => (i === index ? clamp(startWidth + delta) : width)));
    };

    const handleMouseUp = () => {
      resizingRef.current = null;
    };

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

  useEffect(() => {
    return () => {
      releaseAllLocks();
    };
  }, [releaseAllLocks]);

  useEffect(() => {
    if (!autoOpenCreate || !createFromPurchaseOrderId || focusDocId || cloneFromDocId) return;
    if (createFromPurchaseOrderHandledRef.current === createFromPurchaseOrderId) return;

    createFromPurchaseOrderHandledRef.current = createFromPurchaseOrderId;
    startLockTransition(async () => {
      await releaseAllLocks();

      const poResult = await handleGetPurchaseOrderCloneQuantities(createFromPurchaseOrderId);
      if (!poResult || 'error' in poResult || !poResult.success) {
        toast({ title: 'تعذر إنشاء مهمة عمل', description: 'تعذر تحميل بنود أمر الشراء.', variant: 'destructive' });
        return;
      }

      if (!poResult.items.length) {
        toast({ title: 'تعذر إنشاء مهمة عمل', description: 'أمر الشراء لا يحتوي على بنود صالحة.', variant: 'destructive' });
        return;
      }

      rowIdRef.current = 0;
      const generatedItems: Array<InternalTransferItem & { rowId: string }> = poResult.items
        .map((poItem, index) => {
          const rowIndex = rowIdRef.current++;
          const fromWarehouseId = poItem.warehouseId || defaultWarehouseId;
          const toWarehouseId = fromWarehouseId;
          const fromShelfId = poItem.shelfId || getDefaultShelfId(fromWarehouseId);
          const toShelfId = poItem.shelfId || getDefaultShelfId(toWarehouseId) || fromShelfId;
          return {
            lineId: `po-${poResult.orderNumber || 'new'}-${index + 1}`,
            materialId: poItem.materialId,
            quantity: Number(poItem.quantity || 0),
            fromWarehouseId,
            fromShelfId,
            toWarehouseId,
            toShelfId,
            note: `Purchase Order ${poResult.orderNumber || createFromPurchaseOrderId}`,
            unitCostSnapshot: undefined,
            receivedQuantity: 0,
            rejectedQuantity: undefined,
            overReceivedQuantity: undefined,
            overApprovedQuantity: undefined,
            overageStatus: undefined,
            overageSourceShelfId: undefined,
            rowId: `row-${rowIndex}`,
          };
        })
        .filter((item) => Number(item.quantity || 0) > 0 && item.materialId && item.fromWarehouseId && item.fromShelfId && item.toWarehouseId && item.toShelfId);

      if (generatedItems.length === 0) {
        toast({ title: 'تعذر إنشاء مهمة عمل', description: 'فشل تجهيز بنود الإرسالية من أمر الشراء.', variant: 'destructive' });
        return;
      }

      const materialIds = Array.from(new Set(generatedItems.map((item) => item.materialId)));
      const results = await Promise.all(materialIds.map((materialId) => handleAcquireTransferLock({ materialId })));
      const failed = results.find((result) => !result?.success);
      if (failed) {
        toast({ title: 'الصنف مقفول', description: `الصنف قيد النقل من قبل ${failed?.lockedBy || 'مستخدم آخر'}`, variant: 'destructive' });
        return;
      }

      setLockedMaterialIds(new Set(materialIds));
      setItems(generatedItems);
      setFormState({
        date: new Date().toISOString().slice(0, 10),
        enableWarehouseTransfer: true,
        enableShelfTransfer: true,
        allowZeroItems: false,
        note: `Shelf distribution for Purchase Order ${poResult.orderNumber || createFromPurchaseOrderId}`,
      });
      setTransferMeta({
        supplierId: poResult.supplierId,
        supplierName: poResult.supplierName,
        supplierInvoiceNumber: poResult.supplierInvoiceNumber,
        sourcePurchaseOrderId: poResult.orderId,
        sourcePurchaseOrderNumber: poResult.orderNumber,
        sourcePurchaseDocumentType: poResult.sourcePurchaseDocumentType,
      });

      const firstItem = generatedItems[0];
      const fromWarehouseId = firstItem?.fromWarehouseId || defaultWarehouseId;
      const toWarehouseId = firstItem?.toWarehouseId || fromWarehouseId;
      setWarehouseSelection({ fromWarehouseId, toWarehouseId });
      setEditDoc(null);
      setDialogOpen(true);
      toast({ title: 'تم تجهيز مهمة عمل جديدة', description: `تم التحضير مباشرة من أمر الشراء ${poResult.orderNumber || createFromPurchaseOrderId}` });
    });
  }, [autoOpenCreate, cloneFromDocId, createFromPurchaseOrderId, defaultWarehouseId, focusDocId, getDefaultShelfId, releaseAllLocks, toast]);

  useEffect(() => {
    if (!autoOpenCreate || !cloneFromDocId || focusDocId) return;
    if (cloneHandledRef.current === cloneFromDocId) return;
    const sourceDoc = documents.find((doc) => doc.id === cloneFromDocId);
    if (!sourceDoc) return;

    cloneHandledRef.current = cloneFromDocId;
    startLockTransition(async () => {
      await releaseAllLocks();

      if (!sourceDoc.sourcePurchaseOrderId) {
        toast({ title: 'تعذر إعادة الإنشاء', description: 'لا يوجد أمر شراء مرتبط بهذا السند.', variant: 'destructive' });
        return;
      }

      const poResult = await handleGetPurchaseOrderCloneQuantities(sourceDoc.sourcePurchaseOrderId);
      if (!poResult || 'error' in poResult || !poResult.success) {
        toast({ title: 'تعذر إعادة الإنشاء', description: 'تعذر تحميل بنود أمر الشراء الأصلي.', variant: 'destructive' });
        return;
      }

      if (!poResult.items.length) {
        toast({ title: 'تعذر إعادة الإنشاء', description: 'أمر الشراء لا يحتوي على بنود صالحة لإعادة إنشاء الإرسالية.', variant: 'destructive' });
        return;
      }

      const shortageQtyByMaterial = new Map<string, number>();
      for (const sourceItem of sourceDoc.items || []) {
        const materialId = String(sourceItem.materialId || '').trim();
        if (!materialId) continue;
        const shortageQty = Number(
          sourceItem.rejectedQuantity ?? (
            sourceItem.receivedQuantity === undefined
              ? 0
              : Math.max(0, Number(sourceItem.quantity || 0) - Number(sourceItem.receivedQuantity || 0))
          )
        );
        if (shortageQty > 0) {
          shortageQtyByMaterial.set(materialId, (shortageQtyByMaterial.get(materialId) || 0) + shortageQty);
        }
      }

      const shouldUseShortageQuantities = shortageQtyByMaterial.size > 0;

      rowIdRef.current = 0;
      const regeneratedItems: Array<InternalTransferItem & { rowId: string }> = poResult.items
        .map((poItem, index) => {
          const rowIndex = rowIdRef.current++;
          const recreatedQuantity = shouldUseShortageQuantities
            ? Number(shortageQtyByMaterial.get(poItem.materialId) || 0)
            : Number(poItem.quantity || 0);
          const fromWarehouseId = poItem.warehouseId || defaultWarehouseId;
          const toWarehouseId = sourceDoc.enableWarehouseTransfer ? fromWarehouseId : fromWarehouseId;
          const fromShelfId = getDefaultShelfId(fromWarehouseId);
          const toShelfId = sourceDoc.enableShelfTransfer
            ? (poItem.shelfId || getDefaultShelfId(toWarehouseId) || fromShelfId)
            : fromShelfId;
          return {
            lineId: `po-${poResult.orderNumber || sourceDoc.sourcePurchaseOrderNumber || 'recreate'}-${index + 1}`,
            materialId: poItem.materialId,
            quantity: recreatedQuantity,
            fromWarehouseId,
            fromShelfId,
            toWarehouseId,
            toShelfId,
            note: `Purchase Order ${poResult.orderNumber || sourceDoc.sourcePurchaseOrderNumber || sourceDoc.transferNumber}`,
            unitCostSnapshot: undefined,
            receivedQuantity: 0,
            rejectedQuantity: undefined,
            overReceivedQuantity: undefined,
            overApprovedQuantity: undefined,
            overageStatus: undefined,
            overageSourceShelfId: undefined,
            rowId: `row-${rowIndex}`,
          };
        })
        .filter((item) => Number(item.quantity || 0) > 0 && item.materialId && item.fromWarehouseId && item.fromShelfId && item.toWarehouseId && item.toShelfId);

      if (regeneratedItems.length === 0) {
        toast({ title: 'تعذر إعادة الإنشاء', description: 'فشل تكوين بنود الإرسالية من أمر الشراء.', variant: 'destructive' });
        return;
      }

      const materialIds = Array.from(new Set(regeneratedItems.map((item) => item.materialId)));
      const results = await Promise.all(materialIds.map((materialId) => handleAcquireTransferLock({ materialId })));
      const failed = results.find((result) => !result?.success);

      if (failed) {
        toast({ title: 'الصنف مقفول', description: `الصنف قيد النقل من قبل ${failed?.lockedBy || 'مستخدم آخر'}`, variant: 'destructive' });
        return;
      }

      setLockedMaterialIds(new Set(materialIds));
      setItems(regeneratedItems);
      setFormState({
        date: new Date().toISOString().slice(0, 10),
        enableWarehouseTransfer: sourceDoc.enableWarehouseTransfer,
        enableShelfTransfer: sourceDoc.enableShelfTransfer,
        allowZeroItems: sourceDoc.allowZeroItems,
        note: buildRecreateNote(sourceDoc.note, sourceDoc.transferNumber),
      });
      setTransferMeta({
        supplierId: poResult.supplierId,
        supplierName: poResult.supplierName,
        supplierInvoiceNumber: poResult.supplierInvoiceNumber,
        sourcePurchaseOrderId: poResult.orderId,
        sourcePurchaseOrderNumber: poResult.orderNumber,
        sourcePurchaseDocumentType: poResult.sourcePurchaseDocumentType,
      });

      const firstItem = regeneratedItems[0] || sourceDoc.items[0];
      const fromWarehouseId = firstItem?.fromWarehouseId || defaultWarehouseId;
      const toWarehouseId = sourceDoc.enableWarehouseTransfer
        ? firstItem?.toWarehouseId || fromWarehouseId
        : fromWarehouseId;
      setWarehouseSelection({ fromWarehouseId, toWarehouseId });
      setEditDoc(null);
      setDialogOpen(true);
      toast({
        title: 'تم إنشاء سند جديد من المصدر الأصلي',
        description: shouldUseShortageQuantities
          ? `تم التحضير على أساس كمية النقص المسجلة في السند ${sourceDoc.transferNumber}`
          : `تم التحضير من أمر الشراء المرتبط بدل نسخ السند ${sourceDoc.transferNumber}`,
      });
    });
  }, [autoOpenCreate, cloneFromDocId, defaultWarehouseId, documents, focusDocId, getDefaultShelfId, releaseAllLocks, toast]);

  useEffect(() => {
    if (!autoOpenCreate || focusDocId || cloneFromDocId || createFromPurchaseOrderId) return;
    if (createHandledRef.current) return;
    createHandledRef.current = true;
    openCreate();
  }, [autoOpenCreate, cloneFromDocId, createFromPurchaseOrderId, focusDocId]);

  const resetDialog = () => {
    setFormState({
      date: new Date().toISOString().slice(0, 10),
      enableWarehouseTransfer: true,
      enableShelfTransfer: true,
      allowZeroItems: false,
      note: '',
    });
    setWarehouseSelection({ fromWarehouseId: defaultWarehouseId, toWarehouseId: defaultWarehouseId });
    setTransferMeta({});
    setInsufficientStockHint(null);
    setItems([]);
    setBarcodeInput('');
    setEditDoc(null);
  };

  const closeDialog = () => {
    setDialogOpen(false);
    releaseAllLocks();
    resetDialog();
    if (inlineEditDocId || autoOpenCreate) {
      router.push('/admin/data/internal-transfers');
    }
  };

  // When used in page (inline) mode, auto-initialize form for the target document
  useEffect(() => {
    if (!inlineEditDocId) return;
    const doc = documents.find((d) => d.id === inlineEditDocId);
    if (!doc) return;
    rowIdRef.current = 0;
    setItems(
      doc.items.map((item) => {
        const rowIndex = rowIdRef.current++;
        return { ...item, lineId: item.lineId || `line-${rowIndex}`, rowId: `row-${rowIndex}` };
      })
    );
    setFormState({
      date: doc.date,
      enableWarehouseTransfer: doc.enableWarehouseTransfer,
      enableShelfTransfer: doc.enableShelfTransfer,
      allowZeroItems: doc.allowZeroItems,
      note: doc.note || '',
    });
    setTransferMeta({
      supplierId: doc.supplierId,
      supplierName: doc.supplierName,
      supplierInvoiceNumber: doc.supplierInvoiceNumber,
      sourcePurchaseOrderId: doc.sourcePurchaseOrderId,
      sourcePurchaseOrderNumber: doc.sourcePurchaseOrderNumber,
      sourcePurchaseDocumentType: doc.sourcePurchaseDocumentType,
    });
    const firstItem = doc.items[0];
    const fromWh = firstItem?.fromWarehouseId || defaultWarehouseId;
    const toWh = doc.enableWarehouseTransfer ? (firstItem?.toWarehouseId || fromWh) : fromWh;
    setWarehouseSelection({ fromWarehouseId: fromWh, toWarehouseId: toWh });
    setEditDoc(doc);
    setDialogOpen(true);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [inlineEditDocId]);

  const updateItem = (rowId: string, changes: Partial<InternalTransferItem>) => {
    setInsufficientStockHint(null);
    setItems((prev) => prev.map((item) => (item.rowId === rowId ? { ...item, ...changes } : item)));
  };

  const removeItem = (rowId: string) => {
    const target = items.find((item) => item.rowId === rowId);
    if (!target) return;

    startLockTransition(async () => {
      const remainingItems = items.filter((item) => item.rowId !== rowId);
      setItems(remainingItems);
      
      // فك القفل فقط إذا لم يعد هناك أي سطر آخر لنفس الصنف
      const stillUsed = remainingItems.some((item) => item.materialId === target.materialId);
      if (!stillUsed && lockedMaterialIds.has(target.materialId)) {
        await handleReleaseTransferLock({ materialId: target.materialId });
        setLockedMaterialIds((prev) => {
          const next = new Set(prev);
          next.delete(target.materialId);
          return next;
        });
      }
    });
  };

  const addItem = (materialId: string) => {
    startLockTransition(async () => {
      // القفل فقط إذا لم يكن الصنف مقفولاً بالفعل
      if (!lockedMaterialIds.has(materialId)) {
        const lockResult = await handleAcquireTransferLock({ materialId });
        if (!lockResult?.success) {
          toast({ title: 'الصنف مقفول', description: `الصنف قيد النقل من قبل ${lockResult?.lockedBy || 'مستخدم آخر'}`, variant: 'destructive' });
          return;
        }
        setLockedMaterialIds((prev) => new Set(prev).add(materialId));
      }

      const rowIndex = rowIdRef.current++;
      const rowId = `row-${rowIndex}`;
      const lineId = `line-${rowIndex}`;
      const fromWarehouseId = warehouseSelection.fromWarehouseId || defaultWarehouseId || warehouses[0]?.id || '';
      const toWarehouseId = formState.enableWarehouseTransfer
        ? warehouseSelection.toWarehouseId || fromWarehouseId
        : fromWarehouseId;
      const fromShelfId = getDefaultShelfId(fromWarehouseId);
      const baseToShelfId = formState.enableShelfTransfer ? getDefaultShelfId(toWarehouseId) || fromShelfId : fromShelfId;
      const toShelfId = formState.enableWarehouseTransfer && !isWarehouseAllowed(toWarehouseId)
        ? getDefaultShelfId(toWarehouseId) || baseToShelfId
        : baseToShelfId;
      setItems((prev) => [
        ...prev,
        {
          rowId,
          lineId,
          materialId,
          quantity: 1,
          fromWarehouseId,
          fromShelfId,
          toWarehouseId,
          toShelfId,
          note: '',
        },
      ]);
    });
  };

  const openCreate = () => {
    startLockTransition(async () => {
      await releaseAllLocks();
      resetDialog();
      setDialogOpen(true);
    });
  };

  const openEdit = (doc: InternalTransferDocument) => {
    startLockTransition(async () => {
      await releaseAllLocks();
      const materialIds = Array.from(new Set(doc.items.map((item) => item.materialId)));
      const results = await Promise.all(materialIds.map((materialId) => handleAcquireTransferLock({ materialId })));
      const failed = results.find((result) => !result?.success);

      if (failed) {
        toast({ title: 'الصنف مقفول', description: `الصنف قيد النقل من قبل ${failed?.lockedBy || 'مستخدم آخر'}`, variant: 'destructive' });
        return;
      }

      setLockedMaterialIds(new Set(materialIds));
      rowIdRef.current = 0;
      setItems(
        doc.items.map((item) => {
          const rowIndex = rowIdRef.current++;
          return {
            ...item,
            lineId: item.lineId || `line-${rowIndex}`,
            rowId: `row-${rowIndex}`,
          };
        })
      );
      setFormState({
        date: doc.date,
        enableWarehouseTransfer: doc.enableWarehouseTransfer,
        enableShelfTransfer: doc.enableShelfTransfer,
        allowZeroItems: doc.allowZeroItems,
        note: doc.note || '',
      });
      setTransferMeta({
        supplierId: doc.supplierId,
        supplierName: doc.supplierName,
        supplierInvoiceNumber: doc.supplierInvoiceNumber,
        sourcePurchaseOrderId: doc.sourcePurchaseOrderId,
        sourcePurchaseOrderNumber: doc.sourcePurchaseOrderNumber,
        sourcePurchaseDocumentType: doc.sourcePurchaseDocumentType,
      });
      const firstItem = doc.items[0];
      const fromWarehouseId = firstItem?.fromWarehouseId || defaultWarehouseId;
      const toWarehouseId = doc.enableWarehouseTransfer
        ? firstItem?.toWarehouseId || fromWarehouseId
        : fromWarehouseId;
      setWarehouseSelection({ fromWarehouseId, toWarehouseId });
      setEditDoc(doc);
      setDialogOpen(true);
    });
  };

  const onSubmit = () => {
    startSaveTransition(async () => {
      setInsufficientStockHint(null);
      if (items.length === 0) {
        toast({ title: 'لا توجد اصناف', description: 'اضف صنفاً واحداً على الأقل قبل الحفظ.', variant: 'destructive' });
        return;
      }

      const payload = {
        date: formState.date,
        enableWarehouseTransfer: formState.enableWarehouseTransfer,
        enableShelfTransfer: formState.enableShelfTransfer,
        allowZeroItems: formState.allowZeroItems,
        supplierId: transferMeta.supplierId,
        supplierName: transferMeta.supplierName,
        supplierInvoiceNumber: transferMeta.supplierInvoiceNumber,
        sourcePurchaseOrderId: transferMeta.sourcePurchaseOrderId,
        sourcePurchaseOrderNumber: transferMeta.sourcePurchaseOrderNumber,
        sourcePurchaseDocumentType: transferMeta.sourcePurchaseDocumentType,
        note: formState.note || undefined,
        items: items.map(({ rowId, ...item }) => item),
      };

      const result = editDoc
        ? await handleUpdateInternalTransferDocument(editDoc.id, payload)
        : await handleCreateInternalTransferDocument(payload);

      if (!result?.success) {
        if (result?.lockedBy) {
          toast({ title: 'خطأ', description: `الصنف قيد النقل من قبل ${result.lockedBy}`, variant: 'destructive' });
        } else {
          const knownErrors: Record<string, string> = {
            INSUFFICIENT_STOCK_FOR_TRANSFER_DOC: 'لا يمكن حفظ الإرسالية لأن الرصيد غير كافٍ في الرف المصدر.',
          };
          let description = knownErrors[result?.error || ''] || result?.error || 'تعذر حفظ الارسالية.';

          if (result?.error === 'INSUFFICIENT_STOCK_FOR_TRANSFER_DOC') {
            const stockError = result as any;
            const materialId = String(stockError.materialId || '');
            const material = materialById.get(materialId);
            const materialLabel = material ? getMaterialDisplayName(material) : (materialId || 'صنف غير معروف');
            const available = Number(stockError.available || 0);
            const availableLabel = Number.isFinite(available) ? available.toLocaleString('en-US') : '0';
            setInsufficientStockHint({
              materialId,
              fromWarehouseId: String(stockError.fromWarehouseId || ''),
              fromShelfId: String(stockError.fromShelfId || ''),
              requested: Number(stockError.requested || 0),
              available: Number.isFinite(available) ? available : 0,
            });
            description = `الرصيد غير كافٍ للصنف ${materialLabel}. المتاح حالياً: ${availableLabel}.`;
          }

          toast({ title: 'خطأ', description, variant: 'destructive' });
        }
        return;
      }

      await releaseAllLocks();
      toast({ title: editDoc ? 'تم تحديث الارسالية' : 'تم إنشاء الارسالية' });
      resetDialog();
      setDialogOpen(false);
      if (inlineEditDocId || autoOpenCreate) {
        router.push('/admin/data/internal-transfers');
      }
    });
  };

  const onCancel = (docId: string, reason: string) => {
    startCancelTransition(async () => {
      const result = await handleCancelInternalTransferDocument(docId, reason || undefined);
      if (result?.success) {
        toast({ title: 'تم الغاء الارسالية' });
      } else {
        const knownErrors: Record<string, string> = {
          TRANSFER_DOC_HAS_LINKED_ACTIVE_DOCS: 'لا يمكن إلغاء السند لوجود سندات لاحقة مرتبطة به وغير ملغاة.',
          PERIOD_LOCKED: 'لا يمكن الإلغاء داخل فترة مقفلة.',
          INVENTORY_LOCKED: 'لا يمكن الإلغاء بسبب إقفال الجرد.',
          TRANSFER_DOC_REVERSE_FAILED: 'تعذر إنشاء الحركات العكسية اللازمة للإلغاء.',
        };
        toast({
          title: 'خطأ',
          description: knownErrors[result?.error || ''] || result?.error || 'تعذر الغاء الارسالية.',
          variant: 'destructive',
        });
      }
    });
  };

  const addItemFromBarcode = () => {
    const code = barcodeInput.trim();
    if (!code) {
      toast({ title: 'تنبيه', description: 'الرجاء ادخال الباركود.', variant: 'default' });
      return;
    }

    const material = materials.find(
      (m) =>
        m.barcode === code ||
        m.secondaryBarcode === code ||
        m.additionalBarcodes?.includes(code)
    );

    if (!material) {
      toast({ title: 'خطأ', description: 'الباركود غير موجود.', variant: 'destructive' });
      return;
    }

    addItem(material.id);
    setBarcodeInput('');
  };

  const selectMaterialFromPicker = (materialId: string) => {
    addItem(materialId);
    setMaterialPickerOpen(false);
    setMaterialSearch('');
  };

  const getStockQuantity = useCallback(
    (materialId: string, warehouseId: string, shelfId: string): number => {
      const locations = stockLocationsByMaterial[materialId] || [];
      const location = locations.find(
        (loc) => loc.warehouseId === warehouseId && loc.shelfId === shelfId
      );
      return location?.quantity || 0;
    },
    [stockLocationsByMaterial]
  );

  const originalOutgoingByShelf = useMemo(() => {
    const totals = new Map<string, number>();
    if (!editDoc) return totals;

    for (const item of editDoc.items || []) {
      const key = `${item.materialId}::${item.fromWarehouseId}::${item.fromShelfId}`;
      totals.set(key, (totals.get(key) || 0) + Number(item.quantity || 0));
    }

    return totals;
  }, [editDoc]);

  const getEffectiveStockQuantity = useCallback(
    (materialId: string, warehouseId: string, shelfId: string): number => {
      const currentStock = getStockQuantity(materialId, warehouseId, shelfId);
      const key = `${materialId}::${warehouseId}::${shelfId}`;
      const originalOutgoing = originalOutgoingByShelf.get(key) || 0;
      return currentStock + originalOutgoing;
    },
    [getStockQuantity, originalOutgoingByShelf]
  );

  const getUsedQuantityFromShelf = useCallback(
    (currentRowId: string, materialId: string, warehouseId: string, shelfId: string): number => {
      return items
        .filter((item) => item.rowId !== currentRowId && item.materialId === materialId && item.fromWarehouseId === warehouseId && item.fromShelfId === shelfId)
        .reduce((sum, item) => sum + (item.quantity || 0), 0);
    },
    [items]
  );

  const getAvailableQuantityOnShelf = useCallback(
    (currentRowId: string, materialId: string, warehouseId: string, shelfId: string): number => {
      const totalStock = getEffectiveStockQuantity(materialId, warehouseId, shelfId);
      const usedQty = getUsedQuantityFromShelf(currentRowId, materialId, warehouseId, shelfId);
      return Math.max(0, totalStock - usedQty);
    },
    [getEffectiveStockQuantity, getUsedQuantityFromShelf]
  );

  const hasVisibleInsufficientHint = useMemo(() => {
    if (!insufficientStockHint) return false;
    return items.some((item) => {
      if (insufficientStockHint.materialId !== item.materialId) return false;
      if (insufficientStockHint.fromWarehouseId && insufficientStockHint.fromWarehouseId !== item.fromWarehouseId) return false;
      if (insufficientStockHint.fromShelfId && insufficientStockHint.fromShelfId !== item.fromShelfId) return false;
      const available = getAvailableQuantityOnShelf(item.rowId, item.materialId, item.fromWarehouseId, item.fromShelfId);
      return Number(item.quantity || 0) > Number(available || 0);
    });
  }, [getAvailableQuantityOnShelf, insufficientStockHint, items]);

  useEffect(() => {
    if (insufficientStockHint && !hasVisibleInsufficientHint) {
      setInsufficientStockHint(null);
    }
  }, [hasVisibleInsufficientHint, insufficientStockHint]);

  const handleFromWarehouseChange = (value: string) => {
    setInsufficientStockHint(null);
    const fromShelfId = getDefaultShelfId(value);
    const nextToWarehouseId = formState.enableWarehouseTransfer
      ? warehouseSelection.toWarehouseId || value
      : value;
    const baseToShelfId = formState.enableShelfTransfer ? getDefaultShelfId(nextToWarehouseId) || fromShelfId : fromShelfId;
    const toShelfId = formState.enableWarehouseTransfer && !isWarehouseAllowed(nextToWarehouseId)
      ? getDefaultShelfId(nextToWarehouseId) || baseToShelfId
      : baseToShelfId;

    setWarehouseSelection({ fromWarehouseId: value, toWarehouseId: nextToWarehouseId });
    setItems((prev) =>
      prev.map((item) => ({
        ...item,
        fromWarehouseId: value,
        fromShelfId,
        toWarehouseId: nextToWarehouseId,
        toShelfId,
      }))
    );
  };

  const handleToWarehouseChange = (value: string) => {
    setInsufficientStockHint(null);
    const baseToShelfId = getDefaultShelfId(value);
    const toShelfId = formState.enableWarehouseTransfer && !isWarehouseAllowed(value)
      ? getDefaultShelfId(value) || baseToShelfId
      : baseToShelfId;
    setWarehouseSelection((prev) => ({ ...prev, toWarehouseId: value }));
    setItems((prev) =>
      prev.map((item) => ({
        ...item,
        toWarehouseId: value,
        toShelfId: formState.enableShelfTransfer ? toShelfId || item.toShelfId : item.fromShelfId,
      }))
    );
  };

  const isStandaloneCreatePage = Boolean(autoOpenCreate && !focusDocId);
  const isStandaloneEditPage = Boolean(inlineEditDocId);
  const isStandaloneFormPage = isStandaloneCreatePage || isStandaloneEditPage;

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h2 className="text-2xl font-semibold">
            {isStandaloneEditPage ? 'تعديل ارسالية داخلية' : isStandaloneCreatePage ? 'ارسالية داخلية جديدة' : 'الارساليات الداخلية'}
          </h2>
          <p className="text-sm text-muted-foreground">
            {isStandaloneFormPage ? 'نموذج مستقل لإدارة سند الارسالية الداخلية.' : 'سجل ارساليات نقل الاصناف بين المواقع.'}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {(focusDocId || isStandaloneFormPage) && (
            <Button asChild variant="outline">
              <Link href="/admin/data/internal-transfers">العودة للقائمة</Link>
            </Button>
          )}
        {!focusDocId && !isStandaloneFormPage && (
          <Button asChild className="gap-2">
            <Link href="/admin/data/internal-transfers/new">
            <PlusCircle className="h-4 w-4" />
            اضافة ارسالية
            </Link>
          </Button>
        )}
        </div>
      </div>

      {focusDocId && !isStandaloneEditPage && (
        <Card>
          <CardHeader>
            <CardTitle>عرض مباشر للسند {focusedDoc?.transferNumber || focusDocId}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3 text-sm">
            {!focusedDoc ? (
              <p className="text-muted-foreground">لم يتم العثور على السند المطلوب.</p>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-4 gap-2">
                  <div><span className="text-muted-foreground">رقم السند:</span> {focusedDoc.transferNumber}</div>
                  <div><span className="text-muted-foreground">التاريخ:</span> {formatDate(focusedDoc.date)}</div>
                  <div><span className="text-muted-foreground">الحالة:</span> {focusedDoc.status === 'cancelled' ? 'ملغي' : 'نشط'}</div>
                  <div><span className="text-muted-foreground">عدد الأصناف:</span> {focusedDoc.items.length}</div>
                  <div><span className="text-muted-foreground">المورد:</span> {focusedDoc.supplierName || '-'}</div>
                  <div><span className="text-muted-foreground">رقم فاتورة المورد:</span> {focusedDoc.supplierInvoiceNumber || '-'}</div>
                  <div><span className="text-muted-foreground">نوع مستند المورد:</span> {formatSourcePurchaseDocumentType(focusedDoc.sourcePurchaseDocumentType)}</div>
                </div>

                <div className="flex items-center justify-between gap-3 rounded-md border p-2">
                  <div className="text-xs text-muted-foreground">
                    {focusedHasFollowupAction
                      ? `الإلغاء غير متاح: ${focusedFollowupActions[0]?.label || 'يوجد إجراء لاحق فعّال'} - ${focusedFollowupActions[0]?.details || ''}`
                      : 'يمكنك إلغاء السند. سيتم تنفيذ الحركات العكسية تلقائياً إن وجدت.'}
                  </div>
                  <CancelDialog
                    disabled={focusedDoc.status !== 'active' || focusedHasFollowupAction}
                    isLoading={isCancelling}
                    onConfirm={(reason) => onCancel(focusedDoc.id, reason)}
                  />
                </div>

                {focusedFollowupActions.length > 0 && (
                  <div className="rounded-md border p-3 space-y-2">
                    <div className="text-xs font-medium text-muted-foreground">تسلسل الإجراءات اللاحقة (للإلغاء من النهاية إلى البداية)</div>
                    <div className="space-y-1.5">
                      {focusedFollowupActions.map((action, index) => (
                        <div key={`${action.label}-${index}`} className="text-xs space-y-1">
                          <div className="flex items-center gap-2">
                            <span className="text-muted-foreground">{index + 1}.</span>
                            <span className="font-medium">{action.label}:</span>
                            {action.href ? (
                              <a href={action.href} className="underline text-primary">{action.details}</a>
                            ) : (
                              <span>{action.details}</span>
                            )}
                          </div>
                          <div className="ms-5 flex items-center gap-2 text-muted-foreground">
                            <span>رقم السند: {action.transferNumber || focusedDoc.transferNumber}</span>
                            {action.previewHref && (
                              <a href={action.previewHref} className="underline text-primary">معاينة السند</a>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div className="relative w-full overflow-auto rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>الصنف</TableHead>
                        <TableHead>الكمية</TableHead>
                        <TableHead>من</TableHead>
                        <TableHead>إلى</TableHead>
                        <TableHead>ملاحظة</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {focusedDoc.items.map((item, index) => {
                        const material = materialById.get(item.materialId);
                        const fromShelf = warehouseById.get(item.fromWarehouseId)?.shelves?.find((shelf) => shelf.id === item.fromShelfId)?.name || item.fromShelfId;
                        const toShelf = warehouseById.get(item.toWarehouseId)?.shelves?.find((shelf) => shelf.id === item.toShelfId)?.name || item.toShelfId;
                        const distributions = Array.isArray(item.receiptDistributions)
                          ? item.receiptDistributions
                              .map((entry) => {
                                const shelfId = String(entry?.shelfId || '').trim();
                                const qty = Number(entry?.quantity || 0);
                                if (!shelfId || !Number.isFinite(qty) || qty <= 0) return null;
                                const shelfName =
                                  warehouseById.get(item.toWarehouseId)?.shelves?.find((shelf) => shelf.id === shelfId)?.name || shelfId;
                                return { shelfName, qty };
                              })
                              .filter((entry): entry is { shelfName: string; qty: number } => Boolean(entry))
                          : [];
                        return (
                          <TableRow key={`${item.lineId || item.materialId}-${index}`}>
                            <TableCell>{material ? getMaterialDisplayName(material) : item.materialId}</TableCell>
                            <TableCell>{item.quantity}</TableCell>
                            <TableCell>{getWarehouseName(item.fromWarehouseId)} / {fromShelf}</TableCell>
                            <TableCell>
                              <div className="space-y-1">
                                <div>{getWarehouseName(item.toWarehouseId)} / {toShelf}</div>
                                {distributions.length > 0 && (
                                  <div className="text-xs text-muted-foreground">
                                    توزيع: {distributions.map((row) => `${row.shelfName} (${row.qty})`).join(' + ')}
                                  </div>
                                )}
                              </div>
                            </TableCell>
                            <TableCell>{item.note || '-'}</TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      )}

      {!focusDocId && !isStandaloneFormPage && (rows.length === 0 ? (
        <p className="text-sm text-muted-foreground">لا توجد ارساليات داخلية بعد.</p>
      ) : (
        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'all' | 'stuck')} className="space-y-4">
          <TabsList className="grid w-full grid-cols-1 sm:w-auto sm:grid-cols-2">
            <TabsTrigger value="all">ارساليات داخلية ({rows.length})</TabsTrigger>
            <TabsTrigger value="stuck">ارساليات داخلية عالق ({stuckCount})</TabsTrigger>
          </TabsList>

          <div className="grid gap-2 md:grid-cols-6">
            <Input
              className="md:col-span-2"
              placeholder="استعلام: رقم السند، المورد، رقم فاتورة المورد"
              value={searchQuery}
              onChange={(event) => setSearchQuery(event.target.value)}
            />

            <Select value={statusFilter} onValueChange={(value) => setStatusFilter(value as 'all' | 'active' | 'cancelled')}>
              <SelectTrigger>
                <SelectValue placeholder="حالة السند" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل الحالات</SelectItem>
                <SelectItem value="active">نشط</SelectItem>
                <SelectItem value="cancelled">ملغي</SelectItem>
              </SelectContent>
            </Select>

            <Select value={receiptFilter} onValueChange={(value) => setReceiptFilter(value as 'all' | 'pending' | 'partial' | 'received' | 'pending-approval')}>
              <SelectTrigger>
                <SelectValue placeholder="حالة الاستلام" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل حالات الاستلام</SelectItem>
                <SelectItem value="pending">قيد الاستلام</SelectItem>
                <SelectItem value="partial">استلام جزئي</SelectItem>
                <SelectItem value="received">مكتمل</SelectItem>
                <SelectItem value="pending-approval">بانتظار الاعتماد</SelectItem>
              </SelectContent>
            </Select>

            <Select value={createdByFilter} onValueChange={setCreatedByFilter}>
              <SelectTrigger>
                <SelectValue placeholder="أضيف بواسطة" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">كل المستخدمين</SelectItem>
                {uniqueCreators.map((creator) => (
                  <SelectItem key={creator} value={creator}>{creator}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Button
              type="button"
              variant="outline"
              onClick={() => {
                setSearchQuery('');
                setStatusFilter('all');
                setReceiptFilter('all');
                setCreatedByFilter('all');
                setDateFrom('');
                setDateTo('');
              }}
            >
              تصفير الفلاتر
            </Button>
          </div>

          <div className="grid gap-2 sm:grid-cols-2 md:max-w-md">
            <Input type="date" value={dateFrom} onChange={(event) => setDateFrom(event.target.value)} />
            <Input type="date" value={dateTo} onChange={(event) => setDateTo(event.target.value)} />
          </div>

          {filteredRows.length === 0 ? (
            <p className="text-sm text-muted-foreground">لا توجد نتائج مطابقة للفلاتر الحالية.</p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[13%]">رقم الارسالية</TableHead>
                  <TableHead className="w-[20%]">مرجع المورد</TableHead>
                  <TableHead className="w-[10%]">التاريخ</TableHead>
                  <TableHead className="w-[9%]">الحالة</TableHead>
                  <TableHead className="w-[10%]">الكميات</TableHead>
                  <TableHead className="w-[24%]">ملاحظة</TableHead>
                  <TableHead className="w-[8%]">أضيف بواسطة</TableHead>
                  <TableHead className="text-right">الإجراءات</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredRows.map((doc) => (
                  <TableRow key={doc.id}>
                    <TableCell className="font-mono whitespace-nowrap">{doc.transferNumber}</TableCell>
                    <TableCell>
                      <div className="space-y-0.5 text-xs leading-5">
                        <div><span className="text-muted-foreground">المورد:</span> {doc.supplierName || '-'}</div>
                        <div className="font-mono"><span className="text-muted-foreground font-sans">الرقم:</span> {doc.supplierInvoiceNumber || '-'}</div>
                        <div><span className="text-muted-foreground">النوع:</span> {formatSourcePurchaseDocumentType(doc.sourcePurchaseDocumentType)}</div>
                      </div>
                    </TableCell>
                    <TableCell className="font-mono">{formatDate(doc.date)}</TableCell>
                    <TableCell>{doc.status === 'cancelled' ? 'ملغي' : 'نشط'}</TableCell>
                    <TableCell>
                      <div className="space-y-0.5 text-xs leading-5">
                        <div>اصناف: {doc.itemCount}</div>
                        <div>
                          <span className={doc.receivedQty < doc.totalQty ? 'text-amber-600 font-semibold' : 'text-green-600 font-semibold'}>
                            {doc.receivedQty}/{doc.totalQty}
                          </span>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="whitespace-normal break-words text-xs">{doc.note || '-'}</TableCell>
                    <TableCell>{doc.createdBy}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex flex-wrap justify-end gap-2">
                        <Button asChild type="button" variant="outline" size="sm" className="gap-1">
                          <Link href={`/admin/data/internal-transfers/${encodeURIComponent(doc.id)}`}>
                            <Eye className="h-4 w-4" />
                            عرض السند
                          </Link>
                        </Button>
                        {doc.status === 'active' && (doc.effectiveReceiptStatus === 'partial' || doc.effectiveReceiptStatus === 'pending' || (doc.note || '').includes('نقص')) && (
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              setResolveDoc(doc);
                              setResolutionType('supplier');
                              setResolutionNote('');
                              setResolutionMissingCostItems([]);
                            }}
                            disabled={isResolving}
                          >
                            معالجة النقص
                          </Button>
                        )}
                        <Button
                          type="button"
                          size="icon"
                          variant="ghost"
                          onClick={() => router.push(`/admin/data/internal-transfers/${encodeURIComponent(doc.id)}?edit=1`)}
                          disabled={doc.status !== 'active' || isLockPending}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <CancelDialog
                          disabled={doc.status !== 'active'}
                          isLoading={isCancelling}
                          onConfirm={(reason) => onCancel(doc.id, reason)}
                        />
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </Tabs>
      ))}

      <TransferShortageResolutionDialog
        open={Boolean(resolveDoc)}
        onOpenChange={(open) => {
          if (!open) {
            setResolveDoc(null);
            setResolutionNote('');
            setResolutionMissingCostItems([]);
          }
        }}
        transferNumber={resolveDoc?.transferNumber}
        rows={resolveShortageRows}
        total={resolveShortageTotal}
        hasZeroCostRows={hasZeroCostShortageRows}
        resolutionType={resolutionType}
        onResolutionTypeChange={setResolutionType}
        resolutionNote={resolutionNote}
        onResolutionNoteChange={setResolutionNote}
        missingCostItems={resolutionMissingCostItems}
        isPending={isResolving}
        onCancel={() => {
          setResolveDoc(null);
          setResolutionNote('');
          setResolutionMissingCostItems([]);
        }}
        onSave={() => {
          if (!resolveDoc) return;
          startResolveTransition(async () => {
            const result = await handleResolveInternalTransferShortage(resolveDoc.id, {
              resolutionType,
              note: resolutionNote || undefined,
            });
            if (result && !('error' in result)) {
              const entryInfo = result.journalEntryId ? ` • قيد محاسبي: ${result.journalEntryId}` : '';
              const creditNoteInfo = (result as any).creditNoteId ? ` • إشعار دائن: ${(result as any).creditNoteId}` : '';
              toast({ title: 'تمت معالجة النقص', description: `تم الحفظ${entryInfo}${creditNoteInfo}` });
              setResolveDoc(null);
              setResolutionNote('');
              setResolutionMissingCostItems([]);
            } else {
              const knownErrors: Record<string, string> = {
                TRANSFER_SHORTAGE_MISSING_COST_VALUES: 'لا يمكن إنشاء قيد محاسبي بدون تكلفة. يرجى تحديد سعر شراء للأصناف أولاً.',
                'Cannot create journal entry without cost values. Please set purchase prices for items.': 'لا يمكن إنشاء قيد محاسبي بدون تكلفة. يرجى تحديد سعر شراء للأصناف أولاً.',
              };
              const missingCostItems = Array.isArray((result as any)?.missingCostItems)
                ? ((result as any).missingCostItems as MissingCostItem[])
                : [];
              setResolutionMissingCostItems(missingCostItems);
              toast({
                title: 'خطأ',
                description: knownErrors[result?.error || ''] || result?.error || 'تعذر تنفيذ الإجراء.',
                variant: 'destructive',
              });
            }
          });
        }}
      />

      {dialogOpen && (
        <Card>
          <CardHeader>
            <CardTitle>{editDoc ? 'تعديل الارسالية' : 'ارسالية داخلية جديدة'}</CardTitle>
            <p className="text-sm text-muted-foreground">
              {editDoc ? 'قم بتعديل بيانات الارسالية' : 'أنشئ ارسالية نقل اصناف بين المستودعات والرفوف'}
            </p>
          </CardHeader>

          <CardContent className="space-y-4">
            <section className="rounded-lg border bg-background p-3 space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div className="flex items-center gap-3">
                  <span className="min-w-[120px] text-sm font-medium">التاريخ</span>
                  <Input
                    type="date"
                    value={formState.date}
                    onChange={(event) => setFormState((prev) => ({ ...prev, date: event.target.value }))}
                  />
                </div>
                <div className="flex items-center gap-3">
                  <span className="min-w-[120px] text-sm font-medium">ملاحظة عامة</span>
                  <Input
                    value={formState.note}
                    onChange={(event) => setFormState((prev) => ({ ...prev, note: event.target.value }))}
                  />
                </div>
              </div>
              <div className="grid gap-4 sm:grid-cols-2">
                <label className="flex items-center gap-2 text-sm">
                  <Checkbox
                    id="toggle-transfer"
                    checked={formState.enableWarehouseTransfer && formState.enableShelfTransfer}
                    onCheckedChange={(value) => {
                      const checked = Boolean(value);
                      setFormState((prev) => ({
                        ...prev,
                        enableWarehouseTransfer: checked,
                        enableShelfTransfer: checked,
                      }));
                      if (!checked) {
                        setWarehouseSelection((prev) => ({
                          ...prev,
                          toWarehouseId: prev.fromWarehouseId,
                        }));
                        setItems((prev) =>
                          prev.map((item) => ({
                            ...item,
                            toWarehouseId: item.fromWarehouseId,
                            toShelfId: item.fromShelfId,
                          }))
                        );
                        return;
                      }
                      setWarehouseSelection((prev) => ({
                        ...prev,
                        toWarehouseId: prev.toWarehouseId || prev.fromWarehouseId,
                      }));
                      setItems((prev) =>
                        prev.map((item) => ({
                          ...item,
                          toWarehouseId: item.toWarehouseId || item.fromWarehouseId,
                          toShelfId: item.toShelfId || item.fromShelfId,
                        }))
                      );
                    }}
                  />
                  <span className="text-sm font-medium">تفعيل النقل بين المستودعات والرفوف</span>
                </label>
                <label className="flex items-center gap-2 text-sm">
                  <Checkbox
                    id="toggle-zero"
                    checked={formState.allowZeroItems}
                    onCheckedChange={(value) => setFormState((prev) => ({ ...prev, allowZeroItems: Boolean(value) }))}
                  />
                  <span className="text-sm font-medium">السماح بعرض الاصناف برصيد صفر او سالب</span>
                </label>
              </div>
              <div className="rounded-md border bg-muted/30 p-2 text-xs text-muted-foreground">
                عدد الاصناف المضافة: {items.length}
              </div>
            </section>

            <section className="rounded-lg border-2 border-blue-300 bg-blue-50/50 dark:bg-blue-950/20 dark:border-blue-700 p-3 space-y-3 shadow-sm">
              <div className="flex items-center gap-2 mb-2">
                <div className="h-1.5 w-1.5 rounded-full bg-blue-500 animate-pulse"></div>
                <span className="text-xs font-semibold text-blue-700 dark:text-blue-400">إضافة الأصناف</span>
              </div>
              <div className="grid gap-3 sm:grid-cols-[120px_1fr_120px_1fr_auto] sm:items-center">
                <span className="text-sm font-medium">الصنف</span>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setMaterialPickerOpen(true)}
                  className="w-full justify-between h-10"
                >
                  <span>اختر صنف لإضافته</span>
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 opacity-50">
                    <path d="m6 9 6 6 6-6"></path>
                  </svg>
                </Button>
                <span className="text-sm font-medium">الباركود</span>
                <Input
                  value={barcodeInput}
                  onChange={(event) => setBarcodeInput(event.target.value)}
                  onKeyDown={(event) => {
                    if (event.key === 'Enter') {
                      event.preventDefault();
                      addItemFromBarcode();
                    }
                  }}
                  placeholder="امسح الباركود لاضافة الصنف"
                />
                <Button type="button" variant="outline" onClick={addItemFromBarcode} className="w-full sm:w-auto">
                  إضافة بالباركود
                </Button>
              </div>
              <div className="grid gap-3 sm:grid-cols-[120px_1fr_120px_1fr] sm:items-center">
                <span className="text-sm font-medium">من المستودع</span>
                <Select value={warehouseSelection.fromWarehouseId} onValueChange={handleFromWarehouseChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="اختر المستودع" />
                  </SelectTrigger>
                  <SelectContent>
                    {warehouses.map((wh) => (
                      <SelectItem key={wh.id} value={wh.id}>
                        {wh.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <span className="text-sm font-medium">إلى المستودع</span>
                <Select
                  value={formState.enableWarehouseTransfer ? warehouseSelection.toWarehouseId : warehouseSelection.fromWarehouseId}
                  onValueChange={handleToWarehouseChange}
                  disabled={!formState.enableWarehouseTransfer}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="اختر المستودع" />
                  </SelectTrigger>
                  <SelectContent>
                    {warehouses.map((wh) => (
                      <SelectItem key={wh.id} value={wh.id}>
                        {wh.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              {isLockPending && <span className="text-xs text-muted-foreground">جاري التحقق من القفل...</span>}
            </section>

          <section className="rounded-lg border bg-background">
            <div className="flex flex-wrap items-center justify-between gap-2 border-b px-3 py-2">
              <span className="text-sm font-semibold">بنود الارسالية</span>
              <span className="text-xs text-muted-foreground">اسحب حدود الاعمدة لتوسيع الحقول</span>
            </div>
            {hasVisibleInsufficientHint && (
              <div className="border-b border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive">
                يوجد نقص في رصيد أحد البنود. تم تمييز السطر المتأثر وحقل الرف المصدر باللون الأحمر.
              </div>
            )}
            {items.length === 0 ? (
              <div className="p-4 text-sm text-muted-foreground">لم يتم اضافة اصناف بعد.</div>
            ) : (
              <div className="max-h-[320px] max-w-full overflow-auto">
                <Table className="w-full min-w-0 table-fixed border-collapse">
                  <colgroup>
                    {columnWidths.map((width, index) => (
                      <col key={`col-${index}`} style={{ width }} />
                    ))}
                  </colgroup>
                  <TableHeader>
                    <TableRow>
                      {['الصنف', 'الكمية', 'من الرف', 'إلى الرف', 'إزالة'].map((label, index) => (
                        <TableHead key={label} className="relative border-b border-r px-2 py-2">
                          <div className="flex items-center justify-between gap-2">
                            <span className="truncate">{label}</span>
                            <button
                              type="button"
                              aria-label="Resize column"
                              className="h-5 w-1 shrink-0 cursor-col-resize rounded bg-border/70 hover:bg-border"
                              onMouseDown={(event) => {
                                resizingRef.current = {
                                  index,
                                  startX: event.clientX,
                                  startWidth: columnWidths[index],
                                };
                              }}
                            />
                          </div>
                        </TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {items.map((item) => {
                      const material = materialById.get(item.materialId);
                      const availableOnCurrentShelf = getAvailableQuantityOnShelf(item.rowId, item.materialId, item.fromWarehouseId, item.fromShelfId);
                      const matchesHintByMaterial = insufficientStockHint?.materialId === item.materialId;
                      const matchesHintLocation = !insufficientStockHint?.fromWarehouseId || !insufficientStockHint?.fromShelfId
                        ? true
                        : (insufficientStockHint.fromWarehouseId === item.fromWarehouseId && insufficientStockHint.fromShelfId === item.fromShelfId);
                      const isActuallyInsufficient = Number(item.quantity || 0) > Number(availableOnCurrentShelf || 0);
                      const isInsufficientRow = Boolean(matchesHintByMaterial && matchesHintLocation && isActuallyInsufficient);
                      const fromShelves = warehouseById.get(item.fromWarehouseId)?.shelves || [];
                      const toShelves = warehouseById.get(item.toWarehouseId)?.shelves || [];
                      const restrictFromShelf = formState.enableWarehouseTransfer && !isWarehouseAllowed(item.fromWarehouseId);
                      const restrictToShelf = formState.enableWarehouseTransfer && !isWarehouseAllowed(item.toWarehouseId);
                      const fromShelfOptions = restrictFromShelf
                        ? fromShelves.filter((shelf) => shelf.id === getDefaultShelfId(item.fromWarehouseId))
                        : fromShelves;
                      const toShelfOptions = restrictToShelf
                        ? toShelves.filter((shelf) => shelf.id === getDefaultShelfId(item.toWarehouseId))
                        : toShelves;

                      return (
                        <TableRow key={item.rowId} className={`border-b ${isInsufficientRow ? 'bg-destructive/5' : ''}`}>
                          <TableCell className="border-r px-2 py-2">
                            <div
                              className="max-w-full overflow-hidden text-ellipsis whitespace-nowrap"
                              title={material ? getMaterialDisplayName(material) : item.materialId}
                            >
                              {material ? getMaterialDisplayName(material) : item.materialId}
                            </div>
                          </TableCell>
                          <TableCell className="border-r px-2 py-2">
                            <div className="space-y-1">
                              <Input
                                type="number"
                                min="0"
                                max={availableOnCurrentShelf}
                                step="0.01"
                                className="h-9"
                                value={item.quantity}
                                onChange={(event) => {
                                  const maxQty = availableOnCurrentShelf;
                                  const inputQty = Number(event.target.value || 0);
                                  const finalQty = Math.min(inputQty, maxQty);
                                  updateItem(item.rowId, { quantity: finalQty });
                                }}
                              />
                              {formState.enableWarehouseTransfer && (
                                <div className="text-xs text-muted-foreground">
                                  الحد الأقصى: {availableOnCurrentShelf}
                                </div>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="border-r px-2 py-2">
                            <div className="space-y-1">
                              <Select
                                value={item.fromShelfId}
                                onValueChange={(value) => {
                                  const availableOnNewShelf = getAvailableQuantityOnShelf(item.rowId, item.materialId, item.fromWarehouseId, value);
                                  const newQuantity = Math.min(item.quantity, availableOnNewShelf);
                                  updateItem(item.rowId, { fromShelfId: value, quantity: newQuantity > 0 ? newQuantity : 1 });
                                }}
                                disabled={restrictFromShelf}
                              >
                                <SelectTrigger className={`h-9 ${isInsufficientRow ? 'border-destructive text-destructive' : ''}`}>
                                  <SelectValue placeholder="اختر الرف" />
                                </SelectTrigger>
                                <SelectContent>
                                  {fromShelfOptions.map((shelf) => {
                                    const totalQty = getStockQuantity(item.materialId, item.fromWarehouseId, shelf.id);
                                    const availableQty = getAvailableQuantityOnShelf(item.rowId, item.materialId, item.fromWarehouseId, shelf.id);
                                    
                                    // إخفاء الرف إذا تم استهلاك كل الكمية المتوفرة عليه
                                    if (availableQty === 0 && totalQty > 0 && item.fromShelfId !== shelf.id) {
                                      return null;
                                    }

                                    return (
                                      <SelectItem key={shelf.id} value={shelf.id}>
                                        {shelf.name}
                                        {formState.enableWarehouseTransfer && (
                                          <span className={availableQty > 0 ? 'text-green-600' : 'text-red-600'}>
                                            {' '}({availableQty > 0 ? `${availableQty} متاح` : 'غير متوفر'})
                                          </span>
                                        )}
                                      </SelectItem>
                                    );
                                  })}
                                </SelectContent>
                              </Select>
                              {isInsufficientRow && (
                                <div className="text-xs text-destructive">
                                  الرصيد الحالي غير كافٍ لهذا الصنف في هذا الرف. المتاح: {Number(availableOnCurrentShelf || 0).toLocaleString('en-US')}.
                                </div>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="border-r px-2 py-2">
                            <Select
                              value={formState.enableShelfTransfer ? item.toShelfId : item.fromShelfId}
                              onValueChange={(value) => updateItem(item.rowId, { toShelfId: value })}
                              disabled={!formState.enableShelfTransfer || restrictToShelf}
                            >
                              <SelectTrigger className="h-9">
                                <SelectValue placeholder="اختر الرف" />
                              </SelectTrigger>
                              <SelectContent>
                                {toShelfOptions.map((shelf) => {
                                  const qty = formState.enableWarehouseTransfer 
                                    ? getStockQuantity(item.materialId, item.toWarehouseId, shelf.id)
                                    : getStockQuantity(item.materialId, item.fromWarehouseId, shelf.id);
                                  return (
                                    <SelectItem key={shelf.id} value={shelf.id}>
                                      {shelf.name}
                                      {formState.enableWarehouseTransfer && (
                                        <span className={qty > 0 ? 'text-green-600' : 'text-muted-foreground'}>
                                          {' '}({qty > 0 ? `${qty} متوفر` : 'فارغ'})
                                        </span>
                                      )}
                                    </SelectItem>
                                  );
                                })}
                              </SelectContent>
                            </Select>
                          </TableCell>
                          <TableCell className="px-2 py-2 text-right">
                            <Button type="button" size="icon" variant="ghost" onClick={() => removeItem(item.rowId)}>
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            )}
          </section>

          <DialogFooter className="gap-2">
            <Button type="button" variant="outline" onClick={closeDialog}>
              إلغاء
            </Button>
            <Button type="button" onClick={onSubmit} disabled={isSaving || isLockPending}>
              {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              حفظ الارسالية
            </Button>
          </DialogFooter>
          </CardContent>
        </Card>
      )}

      {/* Material Picker Dialog */}
      <Dialog open={materialPickerOpen} onOpenChange={setMaterialPickerOpen}>
        <DialogContent className="max-w-4xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>اختيار صنف</DialogTitle>
            <DialogDescription>ابحث عن الصنف ثم اضغط لإضافته للإرسالية.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <Input
              placeholder="ابحث عن الصنف..."
              value={materialSearch}
              onChange={(e) => setMaterialSearch(e.target.value)}
              autoFocus
            />
            <div className="rounded-md border">
              <div className="relative w-full overflow-auto max-h-[400px]">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>الصنف</TableHead>
                      <TableHead>رقم الصنف</TableHead>
                      <TableHead>الباركود</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {searchedMaterials.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={3} className="text-center text-muted-foreground">
                          لا توجد نتائج
                        </TableCell>
                      </TableRow>
                    ) : (
                      searchedMaterials.map((material) => (
                        <TableRow
                          key={material.id}
                          className="cursor-pointer"
                          onClick={() => selectMaterialFromPicker(material.id)}
                        >
                          <TableCell className="font-medium">{material.name}</TableCell>
                          <TableCell className="font-mono text-xs">{material.itemNumber || '-'}</TableCell>
                          <TableCell className="font-mono text-xs">{material.barcode || '-'}</TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setMaterialPickerOpen(false)}>
              إلغاء
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function CancelDialog({
  disabled,
  isLoading,
  onConfirm,
}: {
  disabled: boolean;
  isLoading: boolean;
  onConfirm: (reason: string) => void;
}) {
  const [reason, setReason] = useState('');

  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <Button type="button" size="icon" variant="ghost" disabled={disabled} className="hidden">
          <Trash2 className="h-4 w-4" />
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>الغاء الارسالية</AlertDialogTitle>
          <AlertDialogDescription>سيتم الغاء الارسالية واعادة رصيد الاصناف.</AlertDialogDescription>
        </AlertDialogHeader>
        <div className="grid gap-2">
          <span className="text-sm">سبب الالغاء (اختياري)</span>
          <Input value={reason} onChange={(event) => setReason(event.target.value)} />
        </div>
        <AlertDialogFooter>
          <AlertDialogCancel>إلغاء</AlertDialogCancel>
          <AlertDialogAction onClick={() => onConfirm(reason)}>
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            الغاء الارسالية
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
