"use client";

import { useEffect, useMemo, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { formatDateStable } from "@/lib/formatters";
import { handleAcquirePurchaseOrderLock, handleCreatePurchaseReturn, handleReleasePurchaseOrderLock } from "@/lib/actions";
import type { ProductionItem, PurchaseOrder, PurchaseReturn, StockLocationBalance, Warehouse } from "@/lib/types";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

interface PurchaseReturnFormProps {
  orders: PurchaseOrder[];
  returns: PurchaseReturn[];
  materials: ProductionItem[];
  warehouses?: Warehouse[];
  stockLocationsByMaterial?: Record<string, StockLocationBalance[]>;
  t?: Record<string, string>;
  tGlobal?: Record<string, string>;
  isRtl?: boolean;
}

type ReturnLine = {
  lineKey: string;
  materialId: string;
  warehouseId: string;
  shelfId: string;
  sourceWarehouseId: string;
  sourceShelfId: string;
  purchasedQty: number;
  previouslyReturnedQty: number;
  remainingQty: number;
  unitPrice: number;
  lineDiscountPercent: number;
  lineDiscountAmount: number;
  returnQty: number;
};

const toNum = (value: unknown) => {
  const num = Number(value || 0);
  return Number.isFinite(num) ? num : 0;
};

const hasFraction = (value: number) => Math.abs(value - Math.round(value)) > 1e-9;

const normalizeSearchText = (value: string) => {
  return String(value || "")
    .toLowerCase()
    .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, "")
    .replace(/[إأآٱ]/g, "ا")
    .replace(/ى/g, "ي")
    .replace(/ؤ/g, "و")
    .replace(/ئ/g, "ي")
    .replace(/ة/g, "ه")
    .replace(/[^\p{L}\p{N}]+/gu, "");
};

export default function PurchaseReturnForm({ orders, returns, materials, warehouses = [], stockLocationsByMaterial = {}, t = {}, tGlobal = {}, isRtl = true }: PurchaseReturnFormProps) {
  const router = useRouter();
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();

  const label = (key: string | undefined, arabic: string, english: string) => {
    const value = key ? t?.[key] : undefined;
    if (typeof value === "string" && value.trim()) return value;
    return isRtl ? arabic : english;
  };

  const globalLabel = (key: string | undefined, arabic: string, english: string) => {
    const value = key ? tGlobal?.[key] : undefined;
    if (typeof value === "string" && value.trim()) return value;
    return isRtl ? arabic : english;
  };

  const [selectedSupplierId, setSelectedSupplierId] = useState("");
  const [selectedOrderId, setSelectedOrderId] = useState("");
  const [lockedOrderId, setLockedOrderId] = useState("");
  const [lockedBy, setLockedBy] = useState("");
  const [itemLookupQuery, setItemLookupQuery] = useState("");

  const getLockFailureMessage = (errorCode: string | undefined) => {
    if (errorCode === "ORDER_CANCELLED") {
      return label(
        "orderCancelledForReturn",
        "لا يمكن إنشاء مردود على فاتورة مشتريات ملغاة.",
        "Cannot create a return for a cancelled purchase invoice."
      );
    }

    if (errorCode === "POSTED_ORDER_EDIT_LOCKED") {
      return label(
        "postedOrderEditLockedDesc",
        "لا يمكن تعديل الفاتورة بعد الترحيل. استخدم إجراء عكسي أو تسوية.",
        "This invoice cannot be edited after posting. Use a reversal or settlement."
      );
    }

    if (errorCode === "ORDER_NOT_FOUND") {
      return label("orderNotFound", "الأمر غير موجود", "Order not found");
    }

    if (errorCode === "Unauthorized") {
      return globalLabel("accessDenied", "غير مصرح", "Unauthorized");
    }

    return label("lockAcquireFailed", "تعذر حجز الفاتورة للتعديل", "Failed to acquire order lock");
  };

  const [returnDate, setReturnDate] = useState(new Date().toISOString().slice(0, 10));
  const [reasonCode, setReasonCode] = useState<"normal" | "employee_error" | "natural_loss">("normal");
  const [returnMode, setReturnMode] = useState<"physical" | "financial_only">("physical");
  const [reasonText, setReasonText] = useState("");

  const [lines, setLines] = useState<ReturnLine[]>([]);

  const materialNameById = useMemo(() => {
    const map = new Map<string, string>();
    materials.forEach((m) => map.set(m.id, m.name || m.id));
    return map;
  }, [materials]);

  const warehouseNameById = useMemo(() => {
    const map = new Map<string, string>();
    warehouses.forEach((w) => map.set(w.id, w.name || w.id));
    return map;
  }, [warehouses]);

  const shelfNameByWarehouseShelf = useMemo(() => {
    const map = new Map<string, string>();
    warehouses.forEach((w) => {
      (w.shelves || []).forEach((shelf) => {
        map.set(`${w.id}||${shelf.id}`, shelf.name || shelf.id);
      });
    });
    return map;
  }, [warehouses]);

  const supplierOptions = useMemo(() => {
    const map = new Map<string, string>();
    orders.forEach((o) => {
      if (!o.supplierId) return;
      map.set(o.supplierId, o.supplierName || o.supplierId);
    });
    return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
  }, [orders]);

  const filteredOrders = useMemo(() => {
    if (!selectedSupplierId) return orders;
    return orders.filter((o) => o.supplierId === selectedSupplierId);
  }, [orders, selectedSupplierId]);

  const selectedOrder = useMemo(() => {
    return filteredOrders.find((o) => o.id === selectedOrderId);
  }, [filteredOrders, selectedOrderId]);

  const selectedOrderReturns = useMemo(() => {
    if (!selectedOrderId) return [];

    return returns
      .filter((ret) => ret.purchaseOrderId === selectedOrderId)
      .map((ret) => {
        const totalQty = (ret.items || []).reduce((sum, item) => sum + toNum(item.quantity), 0);
        return {
          id: ret.id,
          returnNumber: ret.returnNumber,
          date: ret.createdAt || "",
          status: ret.status,
          totalQty,
          totalAmount: toNum(ret.totalAmount),
        };
      })
      .sort((a, b) => new Date(b.date || 0).getTime() - new Date(a.date || 0).getTime());
  }, [returns, selectedOrderId]);

  const materialById = useMemo(() => {
    const map = new Map<string, ProductionItem>();
    materials.forEach((m) => map.set(m.id, m));
    return map;
  }, [materials]);

  const returnedByOrderMaterial = useMemo(() => {
    const map = new Map<string, number>();
    returns
      .filter((ret) => ret.status !== "cancelled")
      .forEach((ret) => {
        (ret.items || []).forEach((item) => {
          const key = `${ret.purchaseOrderId}||${item.materialId}`;
          map.set(key, (map.get(key) || 0) + toNum(item.quantity));
        });
      });
    return map;
  }, [returns]);

  const itemLookupRows = useMemo(() => {
    const query = itemLookupQuery.trim();
    if (!query) return [] as Array<{
      key: string;
      orderId: string;
      orderNumber: string;
      orderDate: string;
      supplierId: string;
      supplierName: string;
      orderStatus: string;
      materialId: string;
      materialName: string;
      purchasedQty: number;
      previouslyReturnedQty: number;
      availableQty: number;
      selectable: boolean;
    }>;

    const tokens = query
      .split(/\s+/)
      .map((part) => normalizeSearchText(part))
      .filter(Boolean);

    if (!tokens.length) return [];

    const matchedMaterialIds = new Set(
      materials
        .filter((material) => {
          const normalizedName = normalizeSearchText(material?.name || "");
          const normalizedNumber = normalizeSearchText(String((material as any)?.itemNumber || material?.id || ""));
          const normalizedBarcode = normalizeSearchText(String((material as any)?.barcode || ""));
          const normalizedExtra = String(((material as any)?.additionalBarcodes || [])
            .map((code: string) => normalizeSearchText(code || ""))
            .join(" "));

          return tokens.every((token) =>
            normalizedName.includes(token) ||
            normalizedNumber.includes(token) ||
            normalizedBarcode.includes(token) ||
            normalizedExtra.includes(token)
          );
        })
        .map((material) => material.id)
    );

    if (!matchedMaterialIds.size) return [];

    const rows: Array<{
      key: string;
      orderId: string;
      orderNumber: string;
      orderDate: string;
      supplierId: string;
      supplierName: string;
      orderStatus: string;
      materialId: string;
      materialName: string;
      purchasedQty: number;
      previouslyReturnedQty: number;
      availableQty: number;
      selectable: boolean;
    }> = [];

    orders.forEach((order) => {
      const purchasedByMaterial = new Map<string, number>();
      (order.items || []).forEach((item) => {
        const materialId = String(item.materialId || "").trim();
        if (!matchedMaterialIds.has(materialId)) return;
        purchasedByMaterial.set(materialId, (purchasedByMaterial.get(materialId) || 0) + toNum(item.quantity));
      });

      purchasedByMaterial.forEach((purchasedQty, materialId) => {
        if (purchasedQty <= 0) return;
        const returnedQty = toNum(returnedByOrderMaterial.get(`${order.id}||${materialId}`));
        const availableQty = Math.max(0, purchasedQty - returnedQty);
        const materialName = materialById.get(materialId)?.name || materialId;

        rows.push({
          key: `${order.id}||${materialId}`,
          orderId: order.id,
          orderNumber: order.orderNumber,
          orderDate: order.date,
          supplierId: order.supplierId,
          supplierName: order.supplierName,
          orderStatus: getOrderStatusLabel(order),
          materialId,
          materialName,
          purchasedQty,
          previouslyReturnedQty: returnedQty,
          availableQty,
          selectable: order.status !== "cancelled" && availableQty > 0,
        });
      });
    });

    return rows.sort((a, b) => {
      const availableDiff = b.availableQty - a.availableQty;
      if (availableDiff !== 0) return availableDiff;
      return new Date(b.orderDate || 0).getTime() - new Date(a.orderDate || 0).getTime();
    });
  }, [itemLookupQuery, materials, materialById, orders, returnedByOrderMaterial]);

  const isWarehouseEnabled = warehouses.length > 0;

  const documentCurrency = String(selectedOrder?.currencyCode || selectedOrder?.baseCurrencyCode || "USD").trim().toUpperCase();
  const documentExchangeRate = toNum(selectedOrder?.exchangeRate || 1);
  const documentWarehouseId = String(selectedOrder?.warehouseId || "").trim();
  const documentWarehouseName = documentWarehouseId ? (warehouseNameById.get(documentWarehouseId) || documentWarehouseId) : "-";
  const autoReturnNumber = label("autoGenerated", "تلقائي عند الحفظ", "Generated on save");
  const configuredReturnTitle = String((t as any)?.purchaseReturnTitle || "").trim();
  const pageTitle = configuredReturnTitle || (isRtl ? "مردود مشتريات" : "Purchase Return");

  const locationBalancesByMaterial = useMemo(() => {
    const map = new Map<string, StockLocationBalance[]>();
    Object.entries(stockLocationsByMaterial || {}).forEach(([materialId, rows]) => {
      const quantityByKey = new Map<string, number>();
      const namesByKey = new Map<string, { warehouseName: string; shelfName: string }>();

      (rows || []).forEach((row) => {
        const normalizedMaterialId = String(row.materialId || materialId || "").trim();
        const warehouseId = String(row.warehouseId || "").trim();
        const shelfId = String(row.shelfId || "").trim();
        const quantity = toNum(row.quantity);
        if (!normalizedMaterialId || !warehouseId || !shelfId || quantity <= 0) return;

        const key = `${warehouseId}::${shelfId}`;
        quantityByKey.set(key, (quantityByKey.get(key) || 0) + quantity);
        namesByKey.set(key, {
          warehouseName: String(row.warehouseName || "").trim() || warehouseId,
          shelfName: String(row.shelfName || "").trim() || shelfId,
        });
      });

      const normalized = Array.from(quantityByKey.entries())
        .map(([key, quantity]) => {
          const [warehouseId, shelfId] = key.split("::");
          const names = namesByKey.get(key);
          return {
            materialId: String(materialId || "").trim(),
            warehouseId,
            warehouseName: names?.warehouseName || warehouseId,
            shelfId,
            shelfName: names?.shelfName || shelfId,
            quantity,
          } as StockLocationBalance;
        })
        .filter((row) => row.quantity > 0)
        .sort((a, b) => Number(b.quantity || 0) - Number(a.quantity || 0));

      map.set(materialId, normalized);
    });
    return map;
  }, [stockLocationsByMaterial]);

  const availableQtyByLocationKey = useMemo(() => {
    const map = new Map<string, number>();
    locationBalancesByMaterial.forEach((rows, materialId) => {
      rows.forEach((row) => {
        const key = `${materialId}||${row.warehouseId}||${row.shelfId}`;
        map.set(key, (map.get(key) || 0) + toNum(row.quantity));
      });
    });
    return map;
  }, [locationBalancesByMaterial]);

  const getLineSourceOptions = (materialId: string) => {
    return locationBalancesByMaterial.get(materialId) || [];
  };

  // Removed custom formatDisplayDate - now use formatDateStable from lib/formatters for consistency

  function getOrderStatusLabel(order: PurchaseOrder) {
    if (order.status === "cancelled") {
      return label("statusCancelled", "ملغي", "Cancelled");
    }

    if (order.status === "received") {
      return label("statusReceived", "مستلم", "Received");
    }

    if (order.postingStatus === "posted") {
      return label("postingPostedLabel", "مرحل", "Posted");
    }

    if (order.postingStatus === "draft") {
      return label("postingDraftLabel", "مسودة", "Draft");
    }

    if (order.postingStatus === "saved") {
      return label("postingSavedLabel", "محفوظ", "Saved");
    }

    return label("statusActive", "نشط", "Active");
  }

  const getReturnStatusLabel = (status: string) => {
    if (status === "posted") return label("statusPosted", "مرحل", "Posted");
    if (status === "approved") return label("statusApproved", "معتمد", "Approved");
    if (status === "draft") return label("statusDraft", "مسودة", "Draft");
    if (status === "locked") return label("statusLocked", "مقفل", "Locked");
    if (status === "cancelled") return label("statusCancelled", "ملغي", "Cancelled");
    return status || "-";
  };

  useEffect(() => {
    if (!selectedSupplierId) return;
    const valid = filteredOrders.some((order) => order.id === selectedOrderId);
    if (!valid) {
      setSelectedOrderId("");
      setLines([]);
    }
  }, [selectedSupplierId, filteredOrders, selectedOrderId]);

  useEffect(() => {
    let mounted = true;

    const run = async () => {
      if (!selectedOrderId) {
        if (lockedOrderId) {
          await handleReleasePurchaseOrderLock(lockedOrderId);
          if (mounted) setLockedOrderId("");
        }
        if (mounted) setLockedBy("");
        return;
      }

      // Avoid reacquiring lock repeatedly for the same selected order.
      if (lockedOrderId === selectedOrderId) {
        if (mounted) setLockedBy("");
        return;
      }

      if (lockedOrderId && lockedOrderId !== selectedOrderId) {
        await handleReleasePurchaseOrderLock(lockedOrderId);
        if (mounted) setLockedOrderId("");
      }

      const lockResult = await handleAcquirePurchaseOrderLock(selectedOrderId);
      if (!mounted) return;
      if (lockResult?.success) {
        setLockedOrderId(selectedOrderId);
        setLockedBy("");
        return;
      }

      const errorCode = String((lockResult as any)?.error || "");
      if (errorCode === "PURCHASE_ORDER_LOCKED") {
        const holder = String((lockResult as any)?.lockedBy || t?.lockedByAnotherUser || "مستخدم آخر");
        setLockedBy(holder);
        toast({
          title: tGlobal?.error || "خطأ",
          description: `${t?.orderLockedWarning || "هذه الفاتورة قيد التعديل من قبل مستخدم آخر"}: ${holder}`,
          variant: "destructive",
        });
        return;
      }

      setLockedBy("");
      toast({
        title: tGlobal?.error || "خطأ",
        description: getLockFailureMessage(errorCode),
        variant: "destructive",
      });
    };

    void run();

    return () => {
      mounted = false;
    };
  }, [selectedOrderId, lockedOrderId, t, tGlobal, toast]);

  useEffect(() => {
    return () => {
      if (lockedOrderId) {
        void handleReleasePurchaseOrderLock(lockedOrderId);
      }
    };
  }, [lockedOrderId]);

  useEffect(() => {
    if (!selectedOrder) {
      setLines([]);
      return;
    }

    const activeReturns = returns.filter((ret) => ret.purchaseOrderId === selectedOrder.id && ret.status !== "cancelled");

    const returnedByKey = new Map<string, number>();
    activeReturns.forEach((ret) => {
      (ret.items || []).forEach((item) => {
        const key = `${item.materialId}||${String(item.warehouseId || "").trim()}||${String(item.shelfId || "").trim()}`;
        returnedByKey.set(key, (returnedByKey.get(key) || 0) + toNum(item.quantity));
      });
    });

    const returnedPoolByKey = new Map(returnedByKey);

    const nextLines: ReturnLine[] = (selectedOrder.items || []).map((item, index) => {
      const materialId = String(item.materialId || "").trim();
      const warehouseId = String((item as any).warehouseId || selectedOrder.warehouseId || "").trim();
      const shelfId = String((item as any).shelfId || "").trim();
      const purchasedQty = toNum(item.quantity);
      const baseKey = `${materialId}||${warehouseId}||${shelfId}`;
      const returnedPool = toNum(returnedPoolByKey.get(baseKey));
      const previouslyReturnedQty = Math.min(purchasedQty, returnedPool);
      returnedPoolByKey.set(baseKey, Math.max(0, returnedPool - previouslyReturnedQty));
      const remainingQty = Math.max(0, purchasedQty - previouslyReturnedQty);

      return {
        lineKey: `${baseKey}||${index}`,
        materialId,
        warehouseId,
        shelfId,
        sourceWarehouseId: warehouseId,
        sourceShelfId: shelfId,
        purchasedQty,
        previouslyReturnedQty,
        remainingQty,
        unitPrice: toNum(item.unitPrice),
        lineDiscountPercent: toNum((item as any).lineDiscountPercent),
        lineDiscountAmount: toNum((item as any).lineDiscountAmount),
        returnQty: 0,
      };
    });

    const nextLinesWithSource = nextLines.map((line) => {
      const sourceOptions = getLineSourceOptions(line.materialId);
      const matchingSource = sourceOptions.find((option) => option.warehouseId === line.warehouseId && option.shelfId === line.shelfId);
      const fallbackSource = sourceOptions[0];
      return {
        ...line,
        sourceWarehouseId: matchingSource?.warehouseId || fallbackSource?.warehouseId || line.warehouseId,
        sourceShelfId: matchingSource?.shelfId || fallbackSource?.shelfId || line.shelfId,
      };
    });

    setLines(nextLinesWithSource);
  }, [selectedOrder, returns, locationBalancesByMaterial]);

  const setReturnQty = (lineKey: string, value: string) => {
    const qty = Math.max(0, toNum(value));
    setLines((prev) => prev.map((line) => {
      if (line.lineKey !== lineKey) return line;
      const material = materialById.get(line.materialId);
      const allowsFractionalQty = Boolean(
        material?.isWeighed ||
        hasFraction(line.purchasedQty) ||
        hasFraction(line.remainingQty)
      );
      const normalizedQty = allowsFractionalQty ? qty : Math.round(qty);
      const bounded = Math.min(normalizedQty, line.remainingQty);
      return { ...line, returnQty: bounded };
    }));
  };

  const setSourceLocation = (lineKey: string, value: string) => {
    const rawValue = String(value || "");
    const separatorIndex = rawValue.indexOf("||");
    const warehouseId = separatorIndex >= 0 ? rawValue.slice(0, separatorIndex) : rawValue;
    const shelfId = separatorIndex >= 0 ? rawValue.slice(separatorIndex + 2) : "";
    setLines((prev) => prev.map((line) => {
      if (line.lineKey !== lineKey) return line;
      return {
        ...line,
        sourceWarehouseId: String(warehouseId || "").trim(),
        sourceShelfId: String(shelfId || "").trim(),
      };
    }));
  };

  const getLineDiscountForQty = (line: ReturnLine) => {
    const gross = line.returnQty * line.unitPrice;
    if (line.lineDiscountPercent > 0) {
      return gross * (line.lineDiscountPercent / 100);
    }
    if (line.lineDiscountAmount > 0 && line.purchasedQty > 0) {
      const discountPerUnit = line.lineDiscountAmount / line.purchasedQty;
      return discountPerUnit * line.returnQty;
    }
    return 0;
  };

  const lineAmounts = useMemo(() => {
    return lines.map((line) => {
      const gross = line.returnQty * line.unitPrice;
      const discount = getLineDiscountForQty(line);
      const total = Math.max(0, gross - discount);
      return { lineKey: line.lineKey, gross, discount, total };
    });
  }, [lines]);

  const amountByLineKey = useMemo(() => {
    const map = new Map<string, { gross: number; discount: number; total: number }>();
    lineAmounts.forEach((a) => map.set(a.lineKey, a));
    return map;
  }, [lineAmounts]);

  const summary = useMemo(() => {
    let gross = 0;
    let discount = 0;
    let total = 0;
    let qty = 0;
    let selectedLines = 0;

    lines.forEach((line) => {
      const amounts = amountByLineKey.get(line.lineKey);
      const lineGross = amounts?.gross || 0;
      const lineDiscount = amounts?.discount || 0;
      const lineTotal = amounts?.total || 0;
      gross += lineGross;
      discount += lineDiscount;
      total += lineTotal;
      qty += line.returnQty;
      if (line.returnQty > 0) selectedLines += 1;
    });

    return { gross, discount, total, qty, selectedLines };
  }, [lines, amountByLineKey]);

  const submit = (postNow: boolean) => {
    if (!selectedOrder) {
      toast({ title: tGlobal?.error || "خطأ", description: t?.chooseOrder || "اختر فاتورة المشتريات", variant: "destructive" });
      return;
    }

    const selectedLines = lines.filter((line) => line.returnQty > 0);
    if (!selectedLines.length) {
      toast({ title: tGlobal?.error || "خطأ", description: t?.noQtySelected || "حدد الكميات المرتجعة أولاً", variant: "destructive" });
      return;
    }

    const invalid = selectedLines.find((line) => line.returnQty > line.remainingQty + 1e-9);
    if (invalid) {
      toast({ title: tGlobal?.error || "خطأ", description: t?.qtyExceedsAvailable || "لا يمكن إرجاع كمية أكبر من المتبقي", variant: "destructive" });
      return;
    }

    const invalidFraction = selectedLines.find((line) => {
      const material = materialById.get(line.materialId);
      const allowsFractionalQty = Boolean(
        material?.isWeighed ||
        hasFraction(line.purchasedQty) ||
        hasFraction(line.remainingQty)
      );
      return !allowsFractionalQty && hasFraction(line.returnQty);
    });
    if (invalidFraction) {
      toast({
        title: tGlobal?.error || "خطأ",
        description: label("fractionalQtyNotAllowed", "هذا الصنف لا يقبل كميات كسرية. أدخل كمية صحيحة بدون كسور", "This item does not allow fractional quantities. Enter a whole number."),
        variant: "destructive",
      });
      return;
    }

    if (returnMode === "physical") {
      const missingSource = selectedLines.find((line) => !line.sourceWarehouseId || !line.sourceShelfId);
      if (missingSource) {
        toast({
          title: globalLabel("error", "خطأ", "Error"),
          description: label("selectSourceLocation", "حدد موقع الإخراج لكل صنف قبل الحفظ", "Select source location for each item before saving"),
          variant: "destructive",
        });
        return;
      }

      const requestedByLocation = new Map<string, number>();
      selectedLines.forEach((line) => {
        const key = `${line.materialId}||${line.sourceWarehouseId}||${line.sourceShelfId}`;
        requestedByLocation.set(key, (requestedByLocation.get(key) || 0) + line.returnQty);
      });

      const exceededKey = Array.from(requestedByLocation.entries()).find(([key, requestedQty]) => {
        const availableQty = availableQtyByLocationKey.get(key) || 0;
        return requestedQty > availableQty + 1e-9;
      });

      if (exceededKey) {
        toast({
          title: globalLabel("error", "خطأ", "Error"),
          description: label("sourceLocationInsufficientQty", "الكمية المطلوبة أكبر من رصيد موقع الإخراج المحدد", "Requested quantity exceeds selected source location balance"),
          variant: "destructive",
        });
        return;
      }
    }

    startTransition(async () => {
      const lock = await handleAcquirePurchaseOrderLock(selectedOrder.id);
      if (!lock?.success) {
        const errorCode = String((lock as any)?.error || "");
        if (errorCode === "PURCHASE_ORDER_LOCKED") {
          const holder = String((lock as any)?.lockedBy || label("lockedByAnotherUser", "مستخدم آخر", "Another user"));
          setLockedBy(holder);
          toast({
            title: globalLabel("error", "خطأ", "Error"),
            description: `${label("orderLockedWarning", "هذه الفاتورة قيد التعديل من قبل مستخدم آخر", "This invoice is being edited by another user")}: ${holder}`,
            variant: "destructive",
          });
          return;
        }

        setLockedBy("");
        toast({
          title: globalLabel("error", "خطأ", "Error"),
          description: getLockFailureMessage(errorCode),
          variant: "destructive",
        });
        return;
      }

      const payload = {
        purchaseOrderId: selectedOrder.id,
        expectedCurrencyCode: documentCurrency,
        items: selectedLines.map((line) => ({
          materialId: line.materialId,
          warehouseId: returnMode === "physical" ? line.sourceWarehouseId : line.warehouseId,
          shelfId: returnMode === "physical" ? line.sourceShelfId : line.shelfId,
          quantity: line.returnQty,
          unitPrice: line.unitPrice,
        })),
        reasonCode,
        returnMode,
        date: returnDate,
        postNow,
      };

      const result = await handleCreatePurchaseReturn(payload);
      await handleReleasePurchaseOrderLock(selectedOrder.id);
      const errorDetails = (result as any)?.errorDetails as
        | {
            materialId?: string;
            warehouseId?: string;
            shelfId?: string;
            requestedQty?: number;
            availableQty?: number;
          }
        | undefined;

      if (!result?.success) {
        if (result?.error === "INSUFFICIENT_STOCK_FOR_REVERSE" && errorDetails) {
          const details = errorDetails;
          const materialName = materialNameById.get(String(details.materialId || "").trim()) || String(details.materialId || "-");
          const warehouseName = warehouseNameById.get(String(details.warehouseId || "").trim()) || String(details.warehouseId || "-");
          const shelfName = shelfNameByWarehouseShelf.get(`${String(details.warehouseId || "").trim()}||${String(details.shelfId || "").trim()}`) || String(details.shelfId || "-");
          toast({
            title: globalLabel("error", "خطأ", "Error"),
            description: `${label("insufficientStockForReverseDetailed", "الكمية غير متوفرة في موقع الإخراج المحدد", "Insufficient stock in selected source location")}: ${materialName} - ${warehouseName}/${shelfName} - ${label("requestedQty", "المطلوب", "Requested")}: ${toNum(details.requestedQty).toFixed(2)} - ${label("availableQty", "المتاح", "Available")}: ${toNum(details.availableQty).toFixed(2)}`,
            variant: "destructive",
          });
          return;
        }

        toast({ title: globalLabel("error", "خطأ", "Error"), description: result?.error || label("returnFailed", "فشل حفظ المردود", "Failed to save the return"), variant: "destructive" });
        return;
      }

      toast({
        title: postNow ? label("returnSuccess", "تم إنشاء مردود المشتريات", "Purchase return created") : label("draftSaved", "تم حفظ المسودة", "Draft saved"),
        description: String(result.returnNumber || ""),
      });

      setReasonText("");
      setLines((prev) => prev.map((line) => ({ ...line, returnQty: 0 })));
      router.refresh();
    });
  };

  return (
    <Card dir={isRtl ? "rtl" : "ltr"}>
      <CardHeader>
        <CardTitle className={isRtl ? "text-right" : "text-left"}>{pageTitle}</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="rounded-lg border bg-muted/20 p-4">
          <div className={isRtl ? "mb-4 text-right" : "mb-4 text-left"}>
            <div className="text-sm font-semibold">{label("documentInfo", "معلومات المستند", "Document Information")}</div>
            <div className="text-xs text-muted-foreground">{label("documentInfoHint", "راجع بيانات المستند قبل تحديد الكميات المرتجعة", "Review document details before selecting return quantities")}</div>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("returnNumber", "رقم المردود", "Return Number")}</Label>
              <Input value={autoReturnNumber} readOnly />
            </div>

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("date", "تاريخ المردود", "Return Date")}</Label>
              <Input type="date" value={returnDate} onChange={(e) => setReturnDate(e.target.value)} />
            </div>

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("supplier", "المورد", "Supplier")}</Label>
              <select
                className="h-10 w-full rounded-md border px-2.5 py-2 text-sm focus:ring-2 focus:ring-ring"
                value={selectedSupplierId}
                onChange={(e) => {
                  setSelectedSupplierId(e.target.value);
                  setSelectedOrderId("");
                  setLines([]);
                }}
              >
                <option value="">{label("chooseSupplier", "اختر المورد", "Choose supplier")}</option>
                {supplierOptions.map((supplier) => (
                  <option key={supplier.id} value={supplier.id}>{supplier.name}</option>
                ))}
              </select>
            </div>

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("order", "الفاتورة الأصلية", "Original Invoice")}</Label>
              <select
                className="h-10 w-full rounded-md border px-2.5 py-2 text-sm focus:ring-2 focus:ring-ring"
                value={selectedOrderId}
                onChange={(e) => setSelectedOrderId(e.target.value)}
              >
                <option value="">{label("chooseOrder", "اختر فاتورة المشتريات", "Choose purchase invoice")}</option>
                {filteredOrders.map((order) => (
                  <option key={order.id} value={order.id} disabled={order.status === "cancelled"}>
                    {order.orderNumber} - {order.supplierName} ({getOrderStatusLabel(order)}){order.status === "cancelled" ? ` - ${label("notAvailable", "غير متاح", "Not available")}` : ""}
                  </option>
                ))}
              </select>
            </div>

            {isWarehouseEnabled && (
              <div className={isRtl ? "text-right" : "text-left"}>
                <Label>{label("warehouse", "المستودع", "Warehouse")}</Label>
                <Input value={documentWarehouseName} readOnly />
              </div>
            )}

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("currencyLabel", "العملة", "Currency")}</Label>
              <Input value={documentCurrency} readOnly />
            </div>

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("exchangeRate", "سعر الصرف", "Exchange Rate")}</Label>
              <Input value={documentExchangeRate} readOnly />
            </div>

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("returnModeLabel", "نوع التسوية", "Settlement Type")}</Label>
              <select
                className="h-10 w-full rounded-md border px-2.5 py-2 text-sm focus:ring-2 focus:ring-ring"
                value={returnMode}
                onChange={(e) => setReturnMode(e.target.value as "physical" | "financial_only")}
              >
                <option value="physical">{label("returnModePhysical", "مردود فعلي (مخزني + مالي)", "Physical return (inventory + financial)")}</option>
                <option value="financial_only">{label("returnModeFinancialOnly", "تسوية مالية فقط (بدون مخزون)", "Financial settlement only (no inventory)")}</option>
              </select>
            </div>

            <div className={isRtl ? "text-right" : "text-left"}>
              <Label>{label("reason", "سبب المردود", "Return Reason")}</Label>
              <select
                className="h-10 w-full rounded-md border px-2.5 py-2 text-sm focus:ring-2 focus:ring-ring"
                value={reasonCode}
                onChange={(e) => setReasonCode(e.target.value as "normal" | "employee_error" | "natural_loss")}
              >
                <option value="normal">{label("reasonNormal", "طبيعي", "Normal")}</option>
                <option value="employee_error">{label("reasonEmployee", "خطأ موظف", "Employee error")}</option>
                <option value="natural_loss">{label("reasonNatural", "هالك طبيعي", "Natural loss")}</option>
              </select>
            </div>

            <div className={isRtl ? "text-right md:col-span-2 xl:col-span-4" : "text-left md:col-span-2 xl:col-span-4"}>
              <Label>{label("returnReasonOptional", "ملاحظة السبب (اختياري)", "Reason Note (Optional)")}</Label>
              <Input value={reasonText} onChange={(e) => setReasonText(e.target.value)} placeholder={label("reasonPlaceholder", "أدخل سببًا توضيحيًا", "Enter an explanatory note")} />
            </div>
          </div>
        </div>

        {lockedBy && (
          <div className="rounded-md border border-destructive/40 bg-destructive/10 p-2 text-xs text-destructive">
            {label("orderLockedWarning", "هذه الفاتورة قيد التعديل من قبل مستخدم آخر", "This invoice is being edited by another user")}: {lockedBy}
          </div>
        )}

        <div className="rounded-md border bg-muted/10 p-3">
          <div className={isRtl ? "mb-2 text-right" : "mb-2 text-left"}>
            <div className="text-sm font-semibold">{label("lookupByItemTitle", "البحث عن الفاتورة عبر الصنف", "Find invoice by item")}</div>
            <div className="text-xs text-muted-foreground">
              {label("lookupByItemHint", "اكتب اسم الصنف أو رقمه أو باركوده لعرض الفواتير التي تحتويه ثم اختر الفاتورة المناسبة.", "Type item name, code, or barcode to list matching invoices and select one.")}
            </div>
          </div>
          <Input
            value={itemLookupQuery}
            onChange={(e) => setItemLookupQuery(e.target.value)}
            placeholder={label("lookupByItemPlaceholder", "ابحث باسم الصنف أو الباركود...", "Search by item name or barcode...")}
          />

          {itemLookupQuery.trim() && (
            <div className="mt-3 rounded-md border overflow-x-auto">
              <Table className="w-full text-sm">
                <TableHeader>
                  <TableRow>
                    <TableHead className={isRtl ? "text-right" : "text-left"}>{label("item", "الصنف", "Item")}</TableHead>
                    <TableHead className="text-center">{label("order", "الفاتورة", "Invoice")}</TableHead>
                    <TableHead className="text-center">{label("supplier", "المورد", "Supplier")}</TableHead>
                    <TableHead className="text-center">{label("status", "الحالة", "Status")}</TableHead>
                    <TableHead className="text-center">{label("purchasedQty", "المشتراة", "Purchased")}</TableHead>
                    <TableHead className="text-center">{label("previouslyReturnedQty", "مرتجع سابقًا", "Returned")}</TableHead>
                    <TableHead className="text-center">{label("availableReturnQty", "المتاح للإرجاع", "Available")}</TableHead>
                    <TableHead className="text-center">{label("actions", "إجراء", "Action")}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {itemLookupRows.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="h-16 text-center text-muted-foreground">
                        {label("lookupNoResults", "لا توجد فواتير مطابقة لهذا الصنف", "No matching invoices for this item")}
                      </TableCell>
                    </TableRow>
                  ) : (
                    itemLookupRows.map((row) => (
                      <TableRow key={row.key}>
                        <TableCell className={isRtl ? "text-right" : "text-left"}>{row.materialName}</TableCell>
                        <TableCell className="text-center">{row.orderNumber}</TableCell>
                        <TableCell className="text-center">{row.supplierName}</TableCell>
                        <TableCell className="text-center">{row.orderStatus}</TableCell>
                        <TableCell className="text-center font-mono">{row.purchasedQty.toFixed(2)}</TableCell>
                        <TableCell className="text-center font-mono">{row.previouslyReturnedQty.toFixed(2)}</TableCell>
                        <TableCell className="text-center font-mono">{row.availableQty.toFixed(2)}</TableCell>
                        <TableCell className="text-center">
                          <Button
                            type="button"
                            size="sm"
                            variant="outline"
                            disabled={!row.selectable || isPending}
                            onClick={() => {
                              setSelectedSupplierId(row.supplierId);
                              setSelectedOrderId(row.orderId);
                              setLockedBy("");
                            }}
                          >
                            {row.selectable
                              ? label("chooseOrder", "اختيار الفاتورة", "Choose")
                              : label("notAvailable", "غير متاح", "Unavailable")}
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </div>

        <div className="rounded-md border bg-muted/10 p-3 text-xs text-muted-foreground">
          {label(
            "sourceLocationNote",
            "مهم: قد تكون الكمية منقولة من الرف الأصلي. اختر موقع الإخراج الفعلي لكل صنف قبل الحفظ.",
            "Important: Quantity may have been moved from original shelf. Choose the actual source location for each item before saving."
          )}
        </div>

        <div className="rounded-md border overflow-x-auto">
          <Table className="w-full table-fixed text-sm [&_th]:border-s [&_th]:border-border/70 [&_th:first-child]:border-s-0 [&_td]:border-s [&_td]:border-border/40 [&_td:first-child]:border-s-0 [&_th]:bg-muted/40 [&_th]:p-2 [&_th]:text-xs [&_th]:font-medium [&_td]:p-2 [&_td]:align-middle [&_input]:h-9 [&_input]:text-sm">
            <TableHeader>
              <TableRow>
                {isRtl ? (
                  <>
                    <TableHead className="w-[58px] text-center">#</TableHead>
                    <TableHead className="w-[260px] text-right">{label("item", "الصنف", "Item")}</TableHead>
                    <TableHead className="w-[210px] text-right">{label("sourceLocation", "موقع الإخراج", "Source Location")}</TableHead>
                    <TableHead className="w-[110px] text-center">{label("purchasedQty", "الكمية المشتراة", "Purchased Qty")}</TableHead>
                    <TableHead className="w-[120px] text-center">{label("previouslyReturnedQty", "الكمية المرتجعة سابقًا", "Previously Returned")}</TableHead>
                    <TableHead className="w-[110px] text-center">{label("availableReturnQty", "الكمية المتاحة للإرجاع", "Available Qty")}</TableHead>
                    <TableHead className="w-[130px] text-center">{label("returnQty", "الكمية المراد إرجاعها", "Return Qty")}</TableHead>
                    <TableHead className="w-[120px] text-center">{label("price", "السعر", "Price")}</TableHead>
                    <TableHead className="w-[120px] text-center">{label("discount", "الخصم", "Discount")}</TableHead>
                    <TableHead className="w-[140px] text-center">{label("total", "الإجمالي", "Total")}</TableHead>
                  </>
                ) : (
                  <>
                    <TableHead className="w-[58px] text-center">#</TableHead>
                    <TableHead className="text-left">{label("item", "الصنف", "Item")}</TableHead>
                    <TableHead className="w-[220px] text-left">{label("sourceLocation", "موقع الإخراج", "Source Location")}</TableHead>
                    <TableHead className="w-[110px] text-center">{label("purchasedQty", "الكمية المشتراة", "Purchased Qty")}</TableHead>
                    <TableHead className="w-[120px] text-center">{label("previouslyReturnedQty", "الكمية المرتجعة سابقًا", "Previously Returned")}</TableHead>
                    <TableHead className="w-[110px] text-center">{label("availableReturnQty", "الكمية المتاحة للإرجاع", "Available Qty")}</TableHead>
                    <TableHead className="w-[130px] text-center">{label("returnQty", "الكمية المراد إرجاعها", "Return Qty")}</TableHead>
                    <TableHead className="w-[120px] text-center">{label("price", "السعر", "Price")}</TableHead>
                    <TableHead className="w-[120px] text-center">{label("discount", "الخصم", "Discount")}</TableHead>
                    <TableHead className="w-[140px] text-center">{label("total", "الإجمالي", "Total")}</TableHead>
                  </>
                )}
              </TableRow>
            </TableHeader>
            <TableBody>
              {!selectedOrder ? (
                <TableRow>
                  <TableCell colSpan={10} className="py-6 text-center text-muted-foreground">
                    {label("chooseOrderFirst", "اختر فاتورة المشتريات أولاً", "Choose a purchase invoice first")}
                  </TableCell>
                </TableRow>
              ) : lines.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={10} className="py-6 text-center text-muted-foreground">
                    {label("noItems", "لا توجد أصناف في هذه الفاتورة", "There are no items in this invoice")}
                  </TableCell>
                </TableRow>
              ) : (
                lines.map((line, index) => {
                  const amounts = amountByLineKey.get(line.lineKey) || { gross: 0, discount: 0, total: 0 };
                  const materialName = materialNameById.get(line.materialId) || line.materialId;
                  const warehouseName = line.warehouseId ? (warehouseNameById.get(line.warehouseId) || line.warehouseId) : "-";
                  const shelfName = line.warehouseId && line.shelfId ? (shelfNameByWarehouseShelf.get(`${line.warehouseId}||${line.shelfId}`) || line.shelfId) : "-";
                  const sourceOptions = getLineSourceOptions(line.materialId);
                  const availableAtSelectedSource = availableQtyByLocationKey.get(`${line.materialId}||${line.sourceWarehouseId}||${line.sourceShelfId}`) || 0;
                  const material = materialById.get(line.materialId);
                  const allowsFractionalQty = Boolean(
                    material?.isWeighed ||
                    hasFraction(line.purchasedQty) ||
                    hasFraction(line.remainingQty)
                  );
                  const discountLabel = line.lineDiscountPercent > 0
                    ? `${line.lineDiscountPercent.toFixed(2)}%`
                    : line.lineDiscountAmount > 0
                      ? line.lineDiscountAmount.toFixed(2)
                      : "0.00";

                  return (
                    <TableRow key={line.lineKey}>
                      {isRtl ? (
                        <>
                          <TableCell className="text-center text-xs text-muted-foreground">{index + 1}</TableCell>
                          <TableCell className="text-right">
                            <div className="font-medium">{materialName}</div>
                            <div className="text-xs text-muted-foreground">{warehouseName}/{shelfName}</div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <select
                                className="h-9 w-full rounded-md border px-2 text-sm"
                                value={`${line.sourceWarehouseId}||${line.sourceShelfId}`}
                                onChange={(event) => setSourceLocation(line.lineKey, event.target.value)}
                                disabled={isPending || returnMode !== "physical" || sourceOptions.length === 0}
                              >
                                {sourceOptions.length === 0 ? (
                                  <option value="">{label("noSourceLocations", "لا توجد مواقع متاحة", "No source locations")}</option>
                                ) : (
                                  sourceOptions.map((option) => (
                                    <option key={`${option.warehouseId}||${option.shelfId}`} value={`${option.warehouseId}||${option.shelfId}`}>
                                      {(option.warehouseName || option.warehouseId)}/{(option.shelfName || option.shelfId)} ({toNum(option.quantity).toFixed(2)})
                                    </option>
                                  ))
                                )}
                              </select>
                              <div className="text-[11px] text-muted-foreground text-right">{label("availableAtSource", "المتاح في موقع الإخراج", "Available at source")}: {availableAtSelectedSource.toFixed(2)}</div>
                              {returnMode !== "physical" && (
                                <div className="text-[11px] text-muted-foreground text-right">{label("financialOnlyIgnoresSource", "في التسوية المالية فقط لا يتم خصم مخزون", "Source is ignored in financial-only mode")}</div>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="text-center font-mono">{line.purchasedQty.toFixed(2)}</TableCell>
                          <TableCell className="text-center font-mono">{line.previouslyReturnedQty.toFixed(2)}</TableCell>
                          <TableCell className="text-center font-mono">{line.remainingQty.toFixed(2)}</TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              min={0}
                              max={line.remainingQty}
                              step={allowsFractionalQty ? 0.01 : 1}
                              value={line.returnQty}
                              onChange={(event) => setReturnQty(line.lineKey, event.target.value)}
                              disabled={isPending || line.remainingQty <= 0}
                              dir="ltr"
                              lang="en"
                              inputMode="decimal"
                            />
                          </TableCell>
                          <TableCell className="text-center font-mono">{line.unitPrice.toFixed(2)}</TableCell>
                          <TableCell className="text-center font-mono">{discountLabel}</TableCell>
                          <TableCell className="text-center font-mono">{amounts.total.toFixed(2)}</TableCell>
                        </>
                      ) : (
                        <>
                          <TableCell className="text-center text-xs text-muted-foreground">{index + 1}</TableCell>
                          <TableCell className="text-left">
                            <div className="font-medium">{materialName}</div>
                            <div className="text-xs text-muted-foreground">{warehouseName}/{shelfName}</div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <select
                                className="h-9 w-full rounded-md border px-2 text-sm"
                                value={`${line.sourceWarehouseId}||${line.sourceShelfId}`}
                                onChange={(event) => setSourceLocation(line.lineKey, event.target.value)}
                                disabled={isPending || returnMode !== "physical" || sourceOptions.length === 0}
                              >
                                {sourceOptions.length === 0 ? (
                                  <option value="">{label("noSourceLocations", "لا توجد مواقع متاحة", "No source locations")}</option>
                                ) : (
                                  sourceOptions.map((option) => (
                                    <option key={`${option.warehouseId}||${option.shelfId}`} value={`${option.warehouseId}||${option.shelfId}`}>
                                      {(option.warehouseName || option.warehouseId)}/{(option.shelfName || option.shelfId)} ({toNum(option.quantity).toFixed(2)})
                                    </option>
                                  ))
                                )}
                              </select>
                              <div className="text-[11px] text-muted-foreground">{label("availableAtSource", "المتاح في موقع الإخراج", "Available at source")}: {availableAtSelectedSource.toFixed(2)}</div>
                            </div>
                          </TableCell>
                          <TableCell className="text-center font-mono">{line.purchasedQty.toFixed(2)}</TableCell>
                          <TableCell className="text-center font-mono">{line.previouslyReturnedQty.toFixed(2)}</TableCell>
                          <TableCell className="text-center font-mono">{line.remainingQty.toFixed(2)}</TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              min={0}
                              max={line.remainingQty}
                              step={allowsFractionalQty ? 0.01 : 1}
                              value={line.returnQty}
                              onChange={(event) => setReturnQty(line.lineKey, event.target.value)}
                              disabled={isPending || line.remainingQty <= 0}
                              dir="ltr"
                              lang="en"
                              inputMode="decimal"
                            />
                          </TableCell>
                          <TableCell className="text-center font-mono">{line.unitPrice.toFixed(2)}</TableCell>
                          <TableCell className="text-center font-mono">{discountLabel}</TableCell>
                          <TableCell className="text-center font-mono">{amounts.total.toFixed(2)}</TableCell>
                        </>
                      )}
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </div>

        <div className="grid grid-cols-2 gap-2 md:grid-cols-4">
          <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
            <div className="text-[11px] text-muted-foreground">{label("selectedLines", "السطور المحددة", "Selected Lines")}</div>
            <div className="font-mono text-sm font-semibold">{summary.selectedLines}</div>
          </div>
          <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
            <div className="text-[11px] text-muted-foreground">{label("qty", "الكمية", "Quantity")}</div>
            <div className="font-mono text-sm font-semibold">{summary.qty.toFixed(2)}</div>
          </div>
          <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
            <div className="text-[11px] text-muted-foreground">{label("discount", "الخصم", "Discount")}</div>
            <div className="font-mono text-sm font-semibold">{summary.discount.toFixed(2)}</div>
          </div>
          <div className="rounded-md border bg-muted/30 px-3 py-2 text-center">
            <div className="text-[11px] text-muted-foreground">{label("grandTotal", "الإجمالي", "Grand Total")}</div>
            <div className="font-mono text-sm font-semibold">{summary.total.toFixed(2)}</div>
          </div>
        </div>

        <div className="rounded-md border bg-muted/10">
          <div className="border-b px-3 py-2 text-sm font-semibold">
            {label("returnsHistoryTitle", "سجل المردودات على هذه الفاتورة", "Returns history for this invoice")}
          </div>
          <div className="overflow-x-auto">
            <Table className="w-full text-sm">
              <TableHeader>
                <TableRow>
                  <TableHead className={isRtl ? "text-right" : "text-left"}>{label("returnNumber", "رقم المردود", "Return Number")}</TableHead>
                  <TableHead className="text-center">{label("date", "التاريخ", "Date")}</TableHead>
                  <TableHead className="text-center">{label("status", "الحالة", "Status")}</TableHead>
                  <TableHead className="text-center">{label("qty", "الكمية", "Quantity")}</TableHead>
                  <TableHead className="text-center">{label("total", "الإجمالي", "Total")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {selectedOrderReturns.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="py-4 text-center text-muted-foreground">
                      {label("noReturnsForOrder", "لا توجد مردودات مسجلة لهذه الفاتورة", "No returns recorded for this invoice")}
                    </TableCell>
                  </TableRow>
                ) : (
                  selectedOrderReturns.map((ret) => (
                    <TableRow key={ret.id}>
                      <TableCell className={isRtl ? "text-right font-medium" : "text-left font-medium"}>{ret.returnNumber || ret.id}</TableCell>
                      <TableCell className="text-center">{formatDateStable(ret.date)}</TableCell>
                      <TableCell className="text-center">{getReturnStatusLabel(ret.status)}</TableCell>
                      <TableCell className="text-center font-mono">{ret.totalQty.toFixed(2)}</TableCell>
                      <TableCell className="text-center font-mono">{ret.totalAmount.toFixed(2)}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </div>

        <div className="flex flex-wrap justify-center gap-2">
          <Button type="button" variant="outline" onClick={() => submit(false)} disabled={isPending || !selectedOrder || Boolean(lockedBy)}>
            {isPending ? label("saving", "جارٍ الحفظ", "Saving") : label("saveDraft", "حفظ كمسودة", "Save as draft")}
          </Button>
          <Button type="button" onClick={() => submit(true)} disabled={isPending || !selectedOrder || Boolean(lockedBy)}>
            {isPending ? label("saving", "جارٍ الحفظ", "Saving") : label("postNow", "حفظ وترحيل", "Save and post")}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
