'use client';

import { useMemo, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { formatDateDDMMYYYY } from '@/lib/utils';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import TransferShortageResolutionDialog, { MissingCostItem, ShortageBreakdownRow } from '@/components/shared/transfer-shortage-resolution-dialog';
import { cn } from '@/lib/utils';
import { useToast } from '@/hooks/use-toast';
import { handleApproveInternalTransferOverage, handleConfirmInternalTransferReceipt, handleResolveInternalTransferShortage, handleSaveInternalTransferReceiptLine } from '@/lib/actions';
import type { InternalTransferDocument, ProductionItem, StockLocationBalance, Warehouse, Employee } from '@/lib/types';
import { AlertTriangle, Check, CheckCircle2, ChevronsUpDown, Loader2, MapPin, XCircle } from 'lucide-react';

type Props = {
  incomingDocuments: InternalTransferDocument[];
  approvalDocuments: InternalTransferDocument[];
  materials: ProductionItem[];
  warehouses: Warehouse[];
  employees: Employee[];
  stockLocationsByMaterial: Record<string, StockLocationBalance[]>;
  historicalShelfKeysByMaterial: Record<string, string[]>;
  userRole?: 'admin' | 'employee' | 'pos';
  allowedSenderWarehouseIds?: string[];
};

function getMaterialName(material?: ProductionItem) {
  if (!material) return '-';
  return material.itemNumber ? `${material.itemNumber} - ${material.name}` : material.name;
}

function isMaterialMatch(material: ProductionItem, code: string) {
  if (!code) return false;
  return (
    material.barcode === code ||
    material.secondaryBarcode === code ||
    material.additionalBarcodes?.includes(code) ||
    false
  );
}
export default function WorkTasksTable({
  incomingDocuments,
  approvalDocuments,
  materials,
  warehouses,
  employees,
  stockLocationsByMaterial,
  historicalShelfKeysByMaterial,
  userRole,
  allowedSenderWarehouseIds,
}: Props) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const router = useRouter();

  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 [receivedState, setReceivedState] = useState<Record<string, number>>({});
  const [barcodeInputs, setBarcodeInputs] = useState<Record<string, string>>({});
  const [overageShelfState, setOverageShelfState] = useState<Record<string, string>>({});
  const [targetShelfState, setTargetShelfState] = useState<Record<string, string>>({});
  const [expandedDocs, setExpandedDocs] = useState<Record<string, boolean>>({});
  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 [hiddenDocIds, setHiddenDocIds] = useState<string[]>([]);
  const [savingLineKey, setSavingLineKey] = useState<string>('');
  const [targetShelfSearchState, setTargetShelfSearchState] = useState<Record<string, string>>({});
  const [targetShelfOpenState, setTargetShelfOpenState] = useState<Record<string, boolean>>({});
  const [distributionEditorOpenState, setDistributionEditorOpenState] = useState<Record<string, boolean>>({});
  const [receiptDistributionState, setReceiptDistributionState] = useState<
    Record<string, Array<{ shelfId: string; quantity: number }>>
  >({});

  const filteredIncomingDocuments = useMemo(
    () => incomingDocuments.filter((doc) => !hiddenDocIds.includes(doc.id)),
    [incomingDocuments, hiddenDocIds]
  );

  const filteredApprovalDocuments = useMemo(
    () => approvalDocuments.filter((doc) => !hiddenDocIds.includes(doc.id)),
    [approvalDocuments, hiddenDocIds]
  );

  const makeKey = (docId: string, lineId: string) => `${docId}::${lineId}`;

  const getLineId = (item: InternalTransferDocument['items'][number], index: number) =>
    item.lineId || `line-${index + 1}`;

  const isResolveOpen = Boolean(resolveDoc);

  const setOverageShelf = (docId: string, lineId: string, shelfId: string) => {
    setOverageShelfState((prev) => ({
      ...prev,
      [makeKey(docId, lineId)]: shelfId,
    }));
  };

  const getShelvesForMaterial = (materialId: string, warehouseId: string) => {
    const shelves = warehouseById.get(warehouseId)?.shelves ?? [];
    const locations = stockLocationsByMaterial[materialId] || [];
    const quantityByShelfId = new Map<string, number>();
    locations
      .filter((loc) => loc.warehouseId === warehouseId)
      .forEach((loc) => {
        quantityByShelfId.set(
          loc.shelfId,
          Number(quantityByShelfId.get(loc.shelfId) || 0) + Number(loc.quantity || 0)
        );
      });

    const currentShelfIds = new Set(
      locations
        .filter((loc) => loc.warehouseId === warehouseId && loc.quantity > 0)
        .map((loc) => loc.shelfId)
    );
    const historicalShelfIds = new Set(
      (historicalShelfKeysByMaterial[materialId] || [])
        .filter((entry) => entry.startsWith(`${warehouseId}||`))
        .map((entry) => entry.split('||')[1])
        .filter(Boolean)
    );

    const currentShelves = shelves
      .filter((shelf) => currentShelfIds.has(shelf.id))
      .sort(
        (a, b) =>
          Number(quantityByShelfId.get(b.id) || 0) - Number(quantityByShelfId.get(a.id) || 0)
          || a.name.localeCompare(b.name, 'ar')
      );
    const historicalShelves = shelves.filter(
      (shelf) => !currentShelfIds.has(shelf.id) && historicalShelfIds.has(shelf.id)
    ).sort((a, b) => a.name.localeCompare(b.name, 'ar'));
    const remainingShelves = shelves.filter(
      (shelf) => !currentShelfIds.has(shelf.id) && !historicalShelfIds.has(shelf.id)
    ).sort((a, b) => a.name.localeCompare(b.name, 'ar'));

    return [...currentShelves, ...historicalShelves, ...remainingShelves];
  };

  const getShelfPriority = (materialId: string, warehouseId: string, shelfId: string): 'current' | 'historical' | 'other' => {
    const locations = stockLocationsByMaterial[materialId] || [];
    const currentShelfIds = new Set(
      locations
        .filter((loc) => loc.warehouseId === warehouseId && Number(loc.quantity || 0) > 0)
        .map((loc) => loc.shelfId)
    );
    if (currentShelfIds.has(shelfId)) return 'current';

    const historicalShelfIds = new Set(
      (historicalShelfKeysByMaterial[materialId] || [])
        .filter((entry) => entry.startsWith(`${warehouseId}||`))
        .map((entry) => entry.split('||')[1])
        .filter(Boolean)
    );
    if (historicalShelfIds.has(shelfId)) return 'historical';

    return 'other';
  };

  const getShelfPriorityLabel = (priority: 'current' | 'historical' | 'other') => {
    if (priority === 'current') return 'يحتوي الصنف الآن';
    if (priority === 'historical') return 'كان يحتوي الصنف سابقاً';
    return 'رف آخر';
  };

  const getShelfPriorityClassName = (priority: 'current' | 'historical' | 'other') => {
    if (priority === 'current') {
      return 'text-emerald-700 bg-emerald-50 border border-emerald-200';
    }
    if (priority === 'historical') {
      return 'text-amber-700 bg-amber-50 border border-amber-200';
    }
    return 'text-slate-600 bg-slate-50 border border-slate-200';
  };

  const getShelvesForWarehouse = (warehouseId: string) => {
    return warehouseById.get(warehouseId)?.shelves ?? [];
  };

  const getMaterialQtyOnShelf = (materialId: string, warehouseId: string, shelfId: string): number => {
    const locations = stockLocationsByMaterial[materialId] || [];
    return locations
      .filter((loc) => loc.warehouseId === warehouseId && loc.shelfId === shelfId)
      .reduce((sum, loc) => sum + Number(loc.quantity || 0), 0);
  };

  const isQuarantineShelfName = (name: string) => {
    const normalized = String(name || '').trim().toLowerCase();
    if (!normalized) return false;
    return normalized.includes('حجر') || normalized.includes('quarantine') || normalized.includes('hold');
  };

  const getQuarantineShelfId = (warehouseId: string) => {
    const shelves = getShelvesForWarehouse(warehouseId);
    return shelves.find((shelf) => isQuarantineShelfName(shelf.name))?.id || '';
  };

  const isQuarantineShelf = (warehouseId: string, shelfId: string) => {
    if (!shelfId) return false;
    const shelf = getShelvesForWarehouse(warehouseId).find((entry) => entry.id === shelfId);
    return shelf ? isQuarantineShelfName(shelf.name) : false;
  };

  const getWarehouseStatus = (warehouse: Warehouse): 'active' | 'stopped' | 'inventory' => {
    if (warehouse.operatingStatus) return warehouse.operatingStatus;
    return warehouse.inactive ? 'stopped' : 'active';
  };

  const getWarehouseManager = (warehouse: Warehouse): string | undefined => {
    if (!warehouse.managerEmployeeId) return undefined;
    const emp = employees.find((e) => e.id === warehouse.managerEmployeeId);
    return emp ? emp.name : warehouse.managerEmployeeId;
  };

  const getWarehouseType = (warehouse: Warehouse): string => {
    return warehouse.warehouseType || 'رئيسي';
  };

  const getShortageBreakdown = (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 ? getMaterialName(material) : item.materialId;
        return {
          materialId: item.materialId,
          materialName,
          shortageQty,
          unitCost,
          totalCost: shortageQty * unitCost,
        };
      })
      .filter((row) => row.shortageQty > 0);
  };

  const resolveShortageRows = useMemo(
    () => (resolveDoc ? getShortageBreakdown(resolveDoc) : []),
    [resolveDoc, materialById]
  );

  const resolveShortageTotal = useMemo(
    () => resolveShortageRows.reduce((sum, row) => sum + row.totalCost, 0),
    [resolveShortageRows]
  );

  const hasZeroCostShortageRows = useMemo(
    () => resolveShortageRows.some((row) => row.unitCost <= 0),
    [resolveShortageRows]
  );


  const setReceived = (docId: string, lineId: string, value: number) => {
    setReceivedState((prev) => ({
      ...prev,
      [makeKey(docId, lineId)]: value,
    }));
  };

  const getSavedDistributions = (item: InternalTransferDocument['items'][number]) => {
    if (!Array.isArray(item.receiptDistributions)) return [];
    return item.receiptDistributions
      .map((entry) => ({
        shelfId: String(entry?.shelfId || '').trim(),
        quantity: Number(entry?.quantity || 0),
      }))
      .filter((entry) => entry.shelfId && Number.isFinite(entry.quantity) && entry.quantity > 0);
  };

  const getLineDistributions = (
    docId: string,
    lineId: string,
    item: InternalTransferDocument['items'][number],
    _defaultShelfId: string
  ) => {
    const key = makeKey(docId, lineId);
    const local = receiptDistributionState[key];
    if (Array.isArray(local)) return local;

    const saved = getSavedDistributions(item);
    if (saved.length > 0) return saved;

    return [];
  };

  const getDistributionTotal = (rows: Array<{ shelfId: string; quantity: number }>) => {
    return rows.reduce((sum, row) => sum + Number(row.quantity || 0), 0);
  };

  const closeResolveDialog = () => {
    setResolveDoc(null);
    setResolutionNote('');
    setResolutionMissingCostItems([]);
  };

  const toggleExpanded = (docId: string) => {
    setExpandedDocs((prev) => ({
      ...prev,
      [docId]: !prev[docId],
    }));
  };

  const canResolveShortage = (doc: InternalTransferDocument) => {
    if (userRole === 'admin') return true;
    if (!allowedSenderWarehouseIds || allowedSenderWarehouseIds.length === 0) return false;
    const fromIds = new Set((doc.items || []).map((item) => item.fromWarehouseId).filter(Boolean));
    return Array.from(fromIds).some((id) => allowedSenderWarehouseIds.includes(id as string));
  };

  const handleBarcode = (doc: InternalTransferDocument) => {
    const raw = barcodeInputs[doc.id] || '';
    const code = raw.trim();
    if (!code) {
      toast({ title: 'تنبيه', description: 'الرجاء إدخال الباركود.' });
      return;
    }

    const matchedMaterial = materials.find((m) => isMaterialMatch(m, code));
    if (!matchedMaterial) {
      toast({ title: 'خطأ', description: 'الباركود غير موجود.', variant: 'destructive' });
      return;
    }

    const targetIndex = doc.items.findIndex((item, index) => {
      const lineId = getLineId(item, index);
      const current = receivedState[makeKey(doc.id, lineId)] ?? item.receivedQuantity ?? 0;
      return item.materialId === matchedMaterial.id && current < item.quantity;
    });

    if (targetIndex === -1) {
      toast({ title: 'تنبيه', description: 'لا يوجد صنف مطابق بحاجة للاستلام.' });
      return;
    }

    const targetItem = doc.items[targetIndex];
    const lineId = getLineId(targetItem, targetIndex);
    setReceived(doc.id, lineId, targetItem.quantity);
    setBarcodeInputs((prev) => ({ ...prev, [doc.id]: '' }));
  };

  const handleConfirm = (doc: InternalTransferDocument) => {
    // Validate target warehouses are active
    const targetWarehouses = new Set(doc.items.map((item) => item.toWarehouseId));
    for (const whId of targetWarehouses) {
      const warehouse = warehouseById.get(whId);
      const isActive = warehouse ? (warehouse.operatingStatus || (warehouse.inactive ? 'stopped' : 'active')) === 'active' : true;
      if (!isActive) {
        toast({
          title: 'تنبيه',
          description: `المستودع المقبول عليه "${warehouse?.name}" في حالة توقف ولا يمكن استقبال الكميات حالياً.`,
          variant: 'destructive',
        });
        return;
      }
    }

    const items = doc.items.map((item, index) => {
      const lineId = getLineId(item, index);
      const key = makeKey(doc.id, lineId);
      const current = receivedState[key] ?? item.receivedQuantity ?? 0;
      const receivedQuantity = Math.max(0, Number(current) || 0);
      const hasOverage = receivedQuantity > item.quantity;
      const shelves = doc.enableShelfTransfer ? getShelvesForMaterial(item.materialId, item.toWarehouseId) : [];
      const defaultShelfId = hasOverage
        ? (getQuarantineShelfId(item.toWarehouseId) || item.toShelfId || shelves[0]?.id || '')
        : (shelves[0]?.id || item.toShelfId || '');
      const selectedShelfId = targetShelfState[key] || defaultShelfId;
      const distributionRows = doc.enableShelfTransfer
        ? getLineDistributions(doc.id, lineId, item, defaultShelfId)
        : [];
      const receiptDistributions = distributionRows
        .map((row) => ({
          shelfId: String(row.shelfId || '').trim(),
          quantity: Number(row.quantity || 0),
        }))
        .filter((row) => row.shelfId && Number.isFinite(row.quantity) && row.quantity > 0);

      return {
        lineId,
        receivedQuantity,
        toShelfId: doc.enableShelfTransfer ? (receiptDistributions[0]?.shelfId || selectedShelfId) : undefined,
        receiptDistributions,
        hasOverage,
        toWarehouseId: item.toWarehouseId,
      };
    });

    if (doc.enableShelfTransfer && items.some((item) => item.receivedQuantity > 0 && item.receiptDistributions.length === 0 && !item.toShelfId)) {
      toast({
        title: 'تنبيه',
        description: 'الرجاء اختيار الرف لكل صنف قبل التأكيد.',
        variant: 'destructive',
      });
      return;
    }

    if (doc.enableShelfTransfer) {
      const hasDistributionMismatch = items.some((entry) => {
        if (entry.receiptDistributions.length === 0) return false;
        const total = getDistributionTotal(entry.receiptDistributions);
        return Math.abs(total - Number(entry.receivedQuantity || 0)) > 0.0001;
      });
      if (hasDistributionMismatch) {
        toast({
          title: 'تنبيه',
          description: 'مجموع كميات التوزيع يجب أن يساوي الكمية المستلمة.',
          variant: 'destructive',
        });
        return;
      }
    }

    if (doc.enableShelfTransfer && items.some((entry) => {
      if (!entry.hasOverage) return false;
      if (entry.receiptDistributions.length > 0) {
        const overageQty = Math.max(0, Number(entry.receivedQuantity || 0) - Number(doc.items.find((row, idx) => getLineId(row, idx) === entry.lineId)?.quantity || 0));
        const quarantineQty = entry.receiptDistributions.reduce((sum, row) => {
          if (!isQuarantineShelf(entry.toWarehouseId, row.shelfId)) return sum;
          return sum + Number(row.quantity || 0);
        }, 0);
        return quarantineQty < overageQty;
      }
      return !isQuarantineShelf(entry.toWarehouseId, entry.toShelfId || '');
    })) {
      toast({
        title: 'تنبيه',
        description: 'لا يمكن تأكيد زيادة إلا على رف حجر مخصص (اسم الرف يحتوي "حجر" أو Quarantine).',
        variant: 'destructive',
      });
      return;
    }

    startTransition(async () => {
      const result = await handleConfirmInternalTransferReceipt(doc.id, {
        items: items.map((item) => ({
          lineId: item.lineId,
          receivedQuantity: item.receivedQuantity,
          toShelfId: item.toShelfId,
          receiptDistributions: item.receiptDistributions,
        })),
      });
      if (result?.success) {
        const shortageMsg = result.shortageNotice
          ? `تم إنشاء ارسالية نقص ${result.shortageNotice.transferNumber} وإشعار المرسل بوجود كميات مفقودة.`
          : undefined;

        const receiptStatus = result.receiptStatus || 'pending';
        const hasPendingOverage = receiptStatus === 'pending-approval';
        const hasShortage = receiptStatus === 'partial';

        if (result.shortageNotice && canResolveShortage(doc)) {
          // افتح حوار معالجة النقص مباشرة بعد التأكيد
          const updatedDoc: InternalTransferDocument = {
            ...doc,
            items: doc.items.map((item, index) => {
              const lineId = getLineId(item, index);
              const current = receivedState[makeKey(doc.id, lineId)] ?? item.receivedQuantity ?? 0;
              const receivedQuantity = Math.max(0, Number(current) || 0);
              const rejectedQuantity = Math.max(0, item.quantity - receivedQuantity);
              return { ...item, receivedQuantity, rejectedQuantity };
            }),
            receiptStatus: 'partial',
          };
          setResolveDoc(updatedDoc);
          setResolutionType('supplier');
          setResolutionNote('');
          setResolutionMissingCostItems([]);
        }

        if (receiptStatus === 'received') {
          setHiddenDocIds((prev) => (prev.includes(doc.id) ? prev : [...prev, doc.id]));
        }

        toast({
          title: receiptStatus === 'received' ? 'تم تأكيد الاستلام' : 'تم حفظ الاستلام مع حالات معلقة',
          description: receiptStatus === 'received'
            ? shortageMsg
            : hasPendingOverage
              ? 'هناك زيادة بانتظار اعتماد المستودع المرسل قبل إغلاق المهمة.'
              : hasShortage
                ? (shortageMsg || 'يوجد نقص ويجب اختيار إجراء معالجة قبل الإغلاق النهائي.')
                : 'تم الحفظ.',
        });
        router.refresh();
        return;
      }
      toast({
        title: 'خطأ',
        description: result?.error === 'OVERAGE_REQUIRES_QUARANTINE_SHELF'
          ? 'الزيادة تتطلب اختيار رف حجر مخصص قبل تأكيد الاستلام.'
          : result?.error === 'RECEIPT_DISTRIBUTION_TOTAL_MISMATCH'
            ? 'مجموع كميات التوزيع يجب أن يساوي الكمية المستلمة.'
            : result?.error === 'TARGET_SHELF_REQUIRED'
              ? 'الرجاء اختيار رف مستلم للسطر.'
              : (result?.error || 'تعذر تأكيد الاستلام.'),
        variant: 'destructive',
      });
    });
  };

  const handleSaveLine = async (
    doc: InternalTransferDocument,
    item: InternalTransferDocument['items'][number],
    index: number
  ) => {
    const lineId = getLineId(item, index);
    const key = makeKey(doc.id, lineId);
    const current = receivedState[key] ?? item.receivedQuantity ?? 0;
    const receivedQuantity = Math.max(0, Number(current) || 0);
    const hasOverage = receivedQuantity > item.quantity;

    const shelves = doc.enableShelfTransfer ? getShelvesForMaterial(item.materialId, item.toWarehouseId) : [];
    const defaultShelfId = hasOverage
      ? (getQuarantineShelfId(item.toWarehouseId) || item.toShelfId || shelves[0]?.id || '')
      : (shelves[0]?.id || item.toShelfId || '');
    const selectedShelfId = targetShelfState[key] || defaultShelfId;
    const distributionRows = doc.enableShelfTransfer
      ? getLineDistributions(doc.id, lineId, item, defaultShelfId)
      : [];
    const receiptDistributions = distributionRows
      .map((row) => ({
        shelfId: String(row.shelfId || '').trim(),
        quantity: Number(row.quantity || 0),
      }))
      .filter((row) => row.shelfId && Number.isFinite(row.quantity) && row.quantity > 0);

    if (doc.enableShelfTransfer && receivedQuantity > 0 && receiptDistributions.length === 0 && !selectedShelfId) {
      toast({
        title: 'تنبيه',
        description: 'الرجاء اختيار الرف قبل حفظ السطر.',
        variant: 'destructive',
      });
      return;
    }

    if (doc.enableShelfTransfer && receiptDistributions.length > 0) {
      const distributionTotal = getDistributionTotal(receiptDistributions);
      if (Math.abs(distributionTotal - receivedQuantity) > 0.0001) {
        toast({
          title: 'تنبيه',
          description: 'مجموع كميات التوزيع يجب أن يساوي الكمية المستلمة.',
          variant: 'destructive',
        });
        return;
      }
    }

    if (doc.enableShelfTransfer && hasOverage) {
      if (receiptDistributions.length > 0) {
        const overageQty = Math.max(0, receivedQuantity - Number(item.quantity || 0));
        const quarantineQty = receiptDistributions.reduce((sum, row) => {
          if (!isQuarantineShelf(item.toWarehouseId, row.shelfId)) return sum;
          return sum + Number(row.quantity || 0);
        }, 0);
        if (quarantineQty < overageQty) {
          toast({
            title: 'تنبيه',
            description: 'عند وجود زيادة يجب أن تكون كمية الزيادة على رف حجر مخصص (اسم الرف يحتوي "حجر" أو Quarantine).',
            variant: 'destructive',
          });
          return;
        }
      } else if (!isQuarantineShelf(item.toWarehouseId, selectedShelfId)) {
        toast({
          title: 'تنبيه',
          description: 'عند وجود زيادة يجب الحفظ على رف حجر مخصص (اسم الرف يحتوي "حجر" أو Quarantine).',
          variant: 'destructive',
        });
        return;
      }
    }

    setSavingLineKey(key);
    try {
      const result = await handleSaveInternalTransferReceiptLine(doc.id, {
        lineId,
        receivedQuantity,
        toShelfId: doc.enableShelfTransfer ? (receiptDistributions[0]?.shelfId || selectedShelfId) : undefined,
        receiptDistributions,
      });

      if (result?.success) {
        toast({ title: 'تم حفظ السطر' });
        router.refresh();
        return;
      }

      toast({
        title: 'خطأ',
        description: result?.error === 'OVERAGE_REQUIRES_QUARANTINE_SHELF'
          ? 'الزيادة تتطلب اختيار رف حجر مخصص قبل حفظ السطر.'
          : result?.error === 'RECEIPT_DISTRIBUTION_TOTAL_MISMATCH'
            ? 'مجموع كميات التوزيع يجب أن يساوي الكمية المستلمة.'
            : result?.error === 'TARGET_SHELF_REQUIRED'
              ? 'الرجاء اختيار رف مستلم للسطر.'
              : (result?.error || 'تعذر حفظ السطر.'),
        variant: 'destructive',
      });
    } finally {
      setSavingLineKey('');
    }
  };

  const handleApproveOverage = (doc: InternalTransferDocument, approved: boolean) => {
    const items = doc.items
      .filter((item) => item.overageStatus === 'pending')
      .map((item, index) => {
        const lineId = getLineId(item, index);
        const shelfId = overageShelfState[makeKey(doc.id, lineId)] || item.fromShelfId;
        return { lineId, sourceShelfId: shelfId };
      });

    startTransition(async () => {
      const result = await handleApproveInternalTransferOverage(doc.id, {
        approved,
        items: approved ? items : undefined,
      });
      if (result?.success) {
        toast({ title: approved ? 'تم اعتماد الزيادة' : 'تم رفض الزيادة' });
        setHiddenDocIds((prev) => (prev.includes(doc.id) ? prev : [...prev, doc.id]));
        router.refresh();
        return;
      }
      toast({
        title: 'خطأ',
        description: result?.error || 'تعذر إتمام الإجراء.',
        variant: 'destructive',
      });
    });
  };

  const hasLocalShortage = (doc: InternalTransferDocument) => {
    return doc.items.some((item, index) => {
      const lineId = getLineId(item, index);
      const current = receivedState[makeKey(doc.id, lineId)] ?? item.receivedQuantity ?? 0;
      return current < item.quantity;
    });
  };

  return (
    <div className="space-y-6">
      <Card className="border">
        <CardHeader className="space-y-1">
          <CardTitle className="text-base">ارساليات بانتظار الاستلام</CardTitle>
          <CardDescription>تأكيد استلام الكميات الواردة للمستودع التابع لك.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {filteredIncomingDocuments.length === 0 ? (
            <div className="text-sm text-muted-foreground">لا توجد ارساليات بانتظار التأكيد حالياً.</div>
          ) : (
            filteredIncomingDocuments.map((doc) => {
              const firstItem = doc.items[0];
              const toWarehouse = firstItem ? warehouseById.get(firstItem.toWarehouseId) : undefined;
              const toWarehouseName = toWarehouse?.name;
              const warehouseStatus = toWarehouse ? getWarehouseStatus(toWarehouse) : 'active';
              const isExpanded = expandedDocs[doc.id] ?? false;
              return (
                <Card key={doc.id} className="border">
                  <CardHeader className="space-y-2">
                    <div className="flex items-start justify-between gap-3">
                      <div className="space-y-2 flex-1">
                        <CardTitle className="text-sm font-semibold">الارسالية {doc.transferNumber}</CardTitle>
                        <CardDescription>
                          {formatDateDDMMYYYY(doc.date)}
                          {toWarehouseName ? ` • المستودع المستلم: ${toWarehouseName}` : ''}
                        </CardDescription>
                        {toWarehouse && (
                          <div className="grid grid-cols-1 gap-1 text-xs mt-2 sm:grid-cols-3">
                            <div className="flex items-center gap-1">
                              <span className="text-muted-foreground">حالة المستودع:</span>
                              <span className={`font-medium ${
                                warehouseStatus === 'active' ? 'text-green-600' :
                                warehouseStatus === 'inventory' ? 'text-amber-600' :
                                'text-gray-600'
                              }`}>
                                {warehouseStatus === 'active' ? 'نشط' :
                                 warehouseStatus === 'inventory' ? 'تحت الجرد' :
                                 'موقوف'}
                              </span>
                            </div>
                            {getWarehouseManager(toWarehouse) && (
                              <div className="flex items-center gap-1">
                                <span className="text-muted-foreground">المسؤول:</span>
                                <span className="font-medium">{getWarehouseManager(toWarehouse)}</span>
                              </div>
                            )}
                            {toWarehouse.city && (
                              <div className="flex items-center gap-1">
                                <span className="text-muted-foreground">المدينة:</span>
                                <span className="font-medium">{toWarehouse.city}</span>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                      <Button variant="ghost" size="sm" onClick={() => toggleExpanded(doc.id)}>
                        {isExpanded ? 'إخفاء التفاصيل' : 'عرض التفاصيل'}
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="text-sm text-muted-foreground flex flex-wrap items-center gap-2">
                      <span>أصناف: {doc.items.length}</span>
                      {hasLocalShortage(doc) && <span className="text-amber-600">يوجد نقص حسب الإدخال الحالي</span>}
                    </div>

                    {isExpanded && (
                      <>
                        <div className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-center">
                          <Input
                            value={barcodeInputs[doc.id] || ''}
                            onChange={(event) =>
                              setBarcodeInputs((prev) => ({ ...prev, [doc.id]: event.target.value }))
                            }
                            onKeyDown={(event) => {
                              if (event.key === 'Enter') {
                                event.preventDefault();
                                handleBarcode(doc);
                              }
                            }}
                            placeholder="امسح الباركود لتأكيد الصنف"
                          />
                          <Button type="button" variant="outline" onClick={() => handleBarcode(doc)}>
                            تأكيد بالباركود
                          </Button>
                        </div>

                        <div className="rounded-md border">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead className="text-start">الصنف</TableHead>
                                <TableHead className="text-center">الكمية المرسلة</TableHead>
                                <TableHead className="text-center">الكمية المستلمة</TableHead>
                                <TableHead className="text-start">الرف المستلم</TableHead>
                                <TableHead className="text-center">الحالة</TableHead>
                                <TableHead className="text-end">حفظ السطر</TableHead>
                                <TableHead className="text-end">مطابقة</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {doc.items.map((item, index) => {
                                const material = materialById.get(item.materialId);
                                const lineId = getLineId(item, index);
                                const key = makeKey(doc.id, lineId);
                                const receivedQty = receivedState[key] ?? item.receivedQuantity ?? 0;
                                const rankedShelves = getShelvesForMaterial(item.materialId, item.toWarehouseId);
                                const rowHasOverage = Number(receivedQty || 0) > Number(item.quantity || 0);
                                const defaultShelfId = rowHasOverage
                                  ? (getQuarantineShelfId(item.toWarehouseId) || item.toShelfId || rankedShelves[0]?.id || '')
                                  : (rankedShelves[0]?.id || item.toShelfId || '');
                                const selectedShelfId = targetShelfState[key] || defaultShelfId;
                                const selectedShelf = rankedShelves.find((shelf) => shelf.id === selectedShelfId);
                                const shelfSearchValue = targetShelfSearchState[key] || '';
                                const filteredShelves = rankedShelves.filter((shelf) => {
                                  const priority = getShelfPriority(item.materialId, item.toWarehouseId, shelf.id);
                                  const haystack = `${shelf.name} ${getShelfPriorityLabel(priority)}`.toLowerCase();
                                  return haystack.includes(shelfSearchValue.trim().toLowerCase());
                                });
                                const distributionRows = getLineDistributions(doc.id, lineId, item, defaultShelfId);
                                const distributionTotal = getDistributionTotal(distributionRows);
                                const hasDistributionMismatch = distributionRows.length > 0 && Math.abs(distributionTotal - Number(receivedQty || 0)) > 0.0001;

                                return (
                                  <TableRow key={`${doc.id}-${lineId}`}>
                                    <TableCell className="text-start">
                                      <div className="space-y-1">
                                        <div>{getMaterialName(material)}</div>
                                      </div>
                                    </TableCell>
                                    <TableCell className="text-center">{item.quantity}</TableCell>
                                    <TableCell className="text-center">
                                      <Input
                                        type="number"
                                        min="0"
                                        className="h-9"
                                        value={receivedQty}
                                        onFocus={(event) => event.currentTarget.select()}
                                        onChange={(event) =>
                                          setReceived(
                                            doc.id,
                                            lineId,
                                            Math.max(0, Number(event.target.value || 0))
                                          )
                                        }
                                      />
                                    </TableCell>
                                      <TableCell className="text-start">
                                        {doc.enableShelfTransfer ? (
                                          <div className="space-y-2">
                                            <div className="flex items-center gap-2">
                                              <Popover
                                                open={Boolean(targetShelfOpenState[key])}
                                                onOpenChange={(open) =>
                                                  setTargetShelfOpenState((prev) => ({
                                                    ...prev,
                                                    [key]: open,
                                                  }))
                                                }
                                              >
                                                <PopoverTrigger asChild>
                                                  <Button
                                                    type="button"
                                                    variant="outline"
                                                    role="combobox"
                                                    aria-expanded={Boolean(targetShelfOpenState[key])}
                                                    className={cn('h-9 min-w-[220px] justify-between', !selectedShelf && 'text-muted-foreground')}
                                                  >
                                                    <span className="truncate">{selectedShelf?.name || 'اختر الرف'}</span>
                                                    <ChevronsUpDown className="ms-2 h-4 w-4 shrink-0 opacity-50" />
                                                  </Button>
                                                </PopoverTrigger>
                                                <PopoverContent className="w-[--radix-popover-trigger-width] p-0">
                                                  <div className="border-b p-2">
                                                    <Input
                                                      placeholder="ابحث عن الرف..."
                                                      value={shelfSearchValue}
                                                      onChange={(event) =>
                                                        setTargetShelfSearchState((prev) => ({
                                                          ...prev,
                                                          [key]: event.target.value,
                                                        }))
                                                      }
                                                      autoFocus
                                                    />
                                                  </div>
                                                  <div className="max-h-64 overflow-y-auto">
                                                    {filteredShelves.length > 0 ? (
                                                      filteredShelves.map((shelf) => {
                                                        const priority = getShelfPriority(item.materialId, item.toWarehouseId, shelf.id);
                                                        const shelfQty = getMaterialQtyOnShelf(item.materialId, item.toWarehouseId, shelf.id);
                                                        return (
                                                          <button
                                                            key={shelf.id}
                                                            type="button"
                                                            className={cn(
                                                              'flex w-full items-center gap-2 px-2 py-1.5 text-start text-sm hover:bg-accent',
                                                              shelf.id === selectedShelfId && 'bg-accent'
                                                            )}
                                                            onClick={() => {
                                                              setTargetShelfState((prev) => ({
                                                                ...prev,
                                                                [key]: shelf.id,
                                                              }));
                                                              setTargetShelfOpenState((prev) => ({
                                                                ...prev,
                                                                [key]: false,
                                                              }));
                                                              setTargetShelfSearchState((prev) => ({
                                                                ...prev,
                                                                [key]: '',
                                                              }));
                                                            }}
                                                          >
                                                            <Check className={cn('h-4 w-4', shelf.id === selectedShelfId ? 'opacity-100' : 'opacity-0')} />
                                                            <span className="flex-1">{shelf.name}</span>
                                                            <span className="text-[11px] text-muted-foreground">{`الرصيد: ${shelfQty.toLocaleString('en-US')}`}</span>
                                                            <span
                                                              className={cn(
                                                                'rounded px-1.5 py-0.5 text-[11px] leading-4',
                                                                getShelfPriorityClassName(priority)
                                                              )}
                                                            >
                                                              {getShelfPriorityLabel(priority)}
                                                            </span>
                                                          </button>
                                                        );
                                                      })
                                                    ) : (
                                                      <div className="px-3 py-4 text-center text-sm text-muted-foreground">
                                                        لا توجد رفوف مطابقة للبحث
                                                      </div>
                                                    )}
                                                  </div>
                                                </PopoverContent>
                                              </Popover>
                                              <Button
                                                type="button"
                                                variant="outline"
                                                size="icon"
                                                className="h-9 w-9 shrink-0"
                                                title="اختيار أفضل رف تلقائياً"
                                                onClick={() => {
                                                  if (selectedShelfId) {
                                                    setTargetShelfState((prev) => ({
                                                      ...prev,
                                                      [key]: selectedShelfId,
                                                    }));
                                                  }
                                                  setTargetShelfSearchState((prev) => ({
                                                    ...prev,
                                                    [key]: '',
                                                  }));
                                                  setTargetShelfOpenState((prev) => ({
                                                    ...prev,
                                                    [key]: true,
                                                  }));
                                                }}
                                              >
                                                <MapPin className="h-4 w-4" />
                                              </Button>
                                              <Button
                                                type="button"
                                                variant="outline"
                                                size="sm"
                                                onClick={() =>
                                                  setDistributionEditorOpenState((prev) => ({
                                                    ...prev,
                                                    [key]: !prev[key],
                                                  }))
                                                }
                                              >
                                                توزيع متعدد
                                              </Button>
                                            </div>

                                            {distributionEditorOpenState[key] && (
                                              <div className="rounded-md border p-2 space-y-2">
                                                <div className="grid grid-cols-[1fr_96px_auto] gap-2 items-center text-[11px] text-muted-foreground">
                                                  <span>الرف</span>
                                                  <span className="text-center">الكمية</span>
                                                  <span className="text-end">حذف</span>
                                                </div>
                                                {distributionRows.map((row, rowIndex) => (
                                                  <div key={`${key}-dist-${rowIndex}`} className="grid grid-cols-[1fr_96px_auto] gap-2 items-center">
                                                    <select
                                                      className="h-9 w-full rounded-md border bg-background px-2 text-sm"
                                                      value={row.shelfId}
                                                      onChange={(event) => {
                                                        const nextRows = [...distributionRows];
                                                        nextRows[rowIndex] = {
                                                          ...nextRows[rowIndex],
                                                          shelfId: event.target.value,
                                                        };
                                                        setReceiptDistributionState((prev) => ({
                                                          ...prev,
                                                          [key]: nextRows,
                                                        }));
                                                      }}
                                                    >
                                                      <option value="">اختر الرف</option>
                                                      {rankedShelves.map((shelf) => (
                                                        <option key={shelf.id} value={shelf.id}>
                                                          {shelf.name}
                                                        </option>
                                                      ))}
                                                    </select>
                                                    <Input
                                                      type="number"
                                                      min="0"
                                                      step="0.001"
                                                      className="h-9"
                                                      value={row.quantity}
                                                      onFocus={(event) => event.currentTarget.select()}
                                                      onChange={(event) => {
                                                        const nextRows = [...distributionRows];
                                                        nextRows[rowIndex] = {
                                                          ...nextRows[rowIndex],
                                                          quantity: Math.max(0, Number(event.target.value || 0)),
                                                        };
                                                        setReceiptDistributionState((prev) => ({
                                                          ...prev,
                                                          [key]: nextRows,
                                                        }));
                                                        setReceived(doc.id, lineId, getDistributionTotal(nextRows));
                                                      }}
                                                    />
                                                    <Button
                                                      type="button"
                                                      variant="ghost"
                                                      size="sm"
                                                      disabled={distributionRows.length <= 1}
                                                      onClick={() => {
                                                        const nextRows = distributionRows.filter((_, idx) => idx !== rowIndex);
                                                        setReceiptDistributionState((prev) => ({
                                                          ...prev,
                                                          [key]: nextRows,
                                                        }));
                                                        setReceived(doc.id, lineId, getDistributionTotal(nextRows));
                                                      }}
                                                    >
                                                      حذف
                                                    </Button>
                                                  </div>
                                                ))}
                                                <div className="flex items-center justify-between gap-2">
                                                  <div className={cn('text-xs', hasDistributionMismatch ? 'text-destructive' : 'text-muted-foreground')}>
                                                    مجموع التوزيع: {distributionTotal.toLocaleString('en-US')} / المستلم: {Number(receivedQty || 0).toLocaleString('en-US')}
                                                  </div>
                                                  <div className="flex gap-2">
                                                    <Button
                                                      type="button"
                                                      variant="outline"
                                                      size="sm"
                                                      onClick={() => {
                                                        const nextRows = [...distributionRows, { shelfId: selectedShelfId || '', quantity: 0 }];
                                                        setReceiptDistributionState((prev) => ({
                                                          ...prev,
                                                          [key]: nextRows,
                                                        }));
                                                        setReceived(doc.id, lineId, getDistributionTotal(nextRows));
                                                      }}
                                                    >
                                                      إضافة رف
                                                    </Button>
                                                    <Button
                                                      type="button"
                                                      variant="ghost"
                                                      size="sm"
                                                      onClick={() => {
                                                        const received = Math.max(0, Number(receivedQty || 0));
                                                        const fallbackShelfId = selectedShelfId || defaultShelfId;
                                                        const nextRows = fallbackShelfId ? [{ shelfId: fallbackShelfId, quantity: received }] : [];
                                                        setReceiptDistributionState((prev) => ({
                                                          ...prev,
                                                          [key]: nextRows,
                                                        }));
                                                        setReceived(doc.id, lineId, getDistributionTotal(nextRows));
                                                      }}
                                                    >
                                                      تعبئة تلقائية
                                                    </Button>
                                                  </div>
                                                </div>
                                              </div>
                                            )}
                                          </div>
                                        ) : (
                                          <span className="text-xs text-muted-foreground">غير مطلوب</span>
                                        )}
                                      </TableCell>
                                      <TableCell className="text-center">
                                        {receivedQty === item.quantity ? (
                                          <span className="text-green-600 text-xs font-medium">مطابق</span>
                                        ) : receivedQty < item.quantity ? (
                                          <span className="text-amber-600 text-xs font-medium">نقص</span>
                                        ) : (
                                          <span className="text-blue-600 text-xs font-medium">زيادة</span>
                                        )}
                                      </TableCell>
                                      <TableCell className="text-end">
                                        <Button
                                          size="sm"
                                          variant="secondary"
                                          disabled={isPending || savingLineKey === key}
                                          onClick={() => handleSaveLine(doc, item, index)}
                                        >
                                          {savingLineKey === key ? <Loader2 className="h-4 w-4 animate-spin" /> : 'حفظ السطر'}
                                        </Button>
                                      </TableCell>
                                    <TableCell className="text-end">
                                      <Button
                                        size="sm"
                                        variant="outline"
                                        onClick={() => setReceived(doc.id, lineId, item.quantity)}
                                      >
                                        مطابقة
                                      </Button>
                                    </TableCell>
                                  </TableRow>
                                );
                              })}
                            </TableBody>
                          </Table>
                        </div>
                      </>
                    )}

                    <div className="flex flex-wrap items-center justify-between gap-3">
                      <div className="text-xs text-muted-foreground">
                        {hasLocalShortage(doc) ? 'يوجد نقص بناءً على الكميات المدخلة.' : ''}
                      </div>
                      <div className="flex gap-2">
                        {canResolveShortage(doc) && (
                          <Button
                            type="button"
                            variant="outline"
                            disabled={!hasLocalShortage(doc) || isPending || isResolveOpen}
                            onClick={() => {
                              if (isResolveOpen) return;
                              const updatedDoc: InternalTransferDocument = {
                                ...doc,
                                items: doc.items.map((item, index) => {
                                  const lineId = getLineId(item, index);
                                  const current = receivedState[makeKey(doc.id, lineId)] ?? item.receivedQuantity ?? 0;
                                  const receivedQuantity = Math.max(0, Number(current) || 0);
                                  const rejectedQuantity = Math.max(0, item.quantity - receivedQuantity);
                                  return { ...item, receivedQuantity, rejectedQuantity };
                                }),
                                receiptStatus: 'partial',
                              };
                              setResolveDoc(updatedDoc);
                              setResolutionType('supplier');
                              setResolutionNote('');
                              setResolutionMissingCostItems([]);
                            }}
                          >
                            معالجة النقص
                          </Button>
                        )}
                        <Button onClick={() => handleConfirm(doc)} disabled={isPending}>
                          {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <CheckCircle2 className="me-2 h-4 w-4" />}
                          تأكيد الاستلام
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })
          )}
        </CardContent>
      </Card>

      <TransferShortageResolutionDialog
        open={Boolean(resolveDoc)}
        onOpenChange={(open) => {
          if (!open) {
            closeResolveDialog();
          }
        }}
        transferNumber={resolveDoc?.transferNumber}
        rows={resolveShortageRows}
        total={resolveShortageTotal}
        hasZeroCostRows={hasZeroCostShortageRows}
        resolutionType={resolutionType}
        onResolutionTypeChange={setResolutionType}
        resolutionNote={resolutionNote}
        onResolutionNoteChange={setResolutionNote}
        missingCostItems={resolutionMissingCostItems}
        isPending={isPending}
        onCancel={closeResolveDialog}
        onSave={() => {
          if (!resolveDoc) return;
          startTransition(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}` });
              setHiddenDocIds((prev) => (prev.includes(resolveDoc.id) ? prev : [...prev, resolveDoc.id]));
              closeResolveDialog();
              router.refresh();
            } 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',
              });
            }
          });
        }}
      />

      <Card className="border">
        <CardHeader className="space-y-1">
          <CardTitle className="text-base flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-amber-500" />
            موافقات زيادات الارساليات
          </CardTitle>
          <CardDescription>تأكيد الزيادة المستلمة من المستودع المستقبل.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {filteredApprovalDocuments.length === 0 ? (
            <div className="text-sm text-muted-foreground">لا توجد زيادات بانتظار الموافقة حالياً.</div>
          ) : (
            filteredApprovalDocuments.map((doc) => {
              const firstItem = doc.items[0];
              const fromWarehouse = firstItem ? warehouseById.get(firstItem.fromWarehouseId) : undefined;
              const fromWarehouseName = fromWarehouse?.name;
              const warehouseStatus = fromWarehouse ? getWarehouseStatus(fromWarehouse) : 'active';
              return (
                <Card key={doc.id} className="border border-amber-200">
                  <CardHeader className="space-y-2">
                    <div>
                      <CardTitle className="text-sm font-semibold">الارسالية {doc.transferNumber}</CardTitle>
                      <CardDescription>
                        {formatDateDDMMYYYY(doc.date)}
                        {fromWarehouseName ? ` • المستودع المرسل: ${fromWarehouseName}` : ''}
                      </CardDescription>
                      {fromWarehouse && (
                        <div className="grid grid-cols-1 gap-1 text-xs mt-2 sm:grid-cols-3">
                          <div className="flex items-center gap-1">
                            <span className="text-muted-foreground">حالة المستودع:</span>
                            <span className={`font-medium ${
                              warehouseStatus === 'active' ? 'text-green-600' :
                              warehouseStatus === 'inventory' ? 'text-amber-600' :
                              'text-gray-600'
                            }`}>
                              {warehouseStatus === 'active' ? 'نشط' :
                               warehouseStatus === 'inventory' ? 'تحت الجرد' :
                               'موقوف'}
                            </span>
                          </div>
                          {getWarehouseManager(fromWarehouse) && (
                            <div className="flex items-center gap-1">
                              <span className="text-muted-foreground">المسؤول:</span>
                              <span className="font-medium">{getWarehouseManager(fromWarehouse)}</span>
                            </div>
                          )}
                          {fromWarehouse.city && (
                            <div className="flex items-center gap-1">
                              <span className="text-muted-foreground">المدينة:</span>
                              <span className="font-medium">{fromWarehouse.city}</span>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="text-start">الصنف</TableHead>
                            <TableHead className="text-center">الكمية المرسلة</TableHead>
                            <TableHead className="text-center">الزيادة المبلغ عنها</TableHead>
                            <TableHead className="text-center">رف المصدر</TableHead>
                            <TableHead className="text-end">الإجراء</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {doc.items
                            .filter((item) => item.overageStatus === 'pending')
                            .map((item, index) => {
                              const material = materialById.get(item.materialId);
                              const lineId = getLineId(item, index);
                              const shelves = getShelvesForMaterial(item.materialId, item.fromWarehouseId);
                              const shelfValue =
                                overageShelfState[makeKey(doc.id, lineId)] ||
                                shelves.find((shelf) => shelf.id === item.fromShelfId)?.id ||
                                shelves[0]?.id ||
                                '';
                              return (
                                <TableRow key={`${doc.id}-${lineId}`}>
                                  <TableCell className="text-start">{getMaterialName(material)}</TableCell>
                                  <TableCell className="text-center">{item.quantity}</TableCell>
                                  <TableCell className="text-center">{item.overReceivedQuantity ?? 0}</TableCell>
                                  <TableCell className="text-center">
                                    <select
                                      className="h-9 w-full rounded-md border border-input bg-background px-2 text-sm"
                                      value={shelfValue}
                                      onChange={(event) => setOverageShelf(doc.id, lineId, event.target.value)}
                                    >
                                      {shelves.map((shelf) => (
                                        <option key={shelf.id} value={shelf.id}>
                                          {shelf.name}
                                        </option>
                                      ))}
                                    </select>
                                  </TableCell>
                                  <TableCell className="text-end">
                                    <div className="flex justify-end gap-2">
                                      <Button
                                        size="sm"
                                        variant="outline"
                                        onClick={() => handleApproveOverage(doc, true)}
                                        disabled={isPending}
                                        className="text-green-600 border-green-600 hover:bg-green-50 hover:text-green-700"
                                      >
                                        {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <CheckCircle2 className="me-2 h-4 w-4" />}
                                        اعتماد
                                      </Button>
                                      <Button
                                        size="sm"
                                        variant="outline"
                                        onClick={() => handleApproveOverage(doc, false)}
                                        disabled={isPending}
                                        className="text-red-600 border-red-600 hover:bg-red-50 hover:text-red-700"
                                      >
                                        {isPending ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <XCircle className="me-2 h-4 w-4" />}
                                        رفض
                                      </Button>
                                    </div>
                                  </TableCell>
                                </TableRow>
                              );
                            })}
                        </TableBody>
                      </Table>
                    </div>
                  </CardContent>
                </Card>
              );
            })
          )}
        </CardContent>
      </Card>
    </div>
  );
}
