import { verifySession } from "@/lib/auth";
import { getCurrentLocale, getTranslations } from "@/lib/i18n";

import { pgGetInventoryMovements, pgGetInternalTransfers, pgGetInvoices, pgGetMaterials, pgGetPurchaseOrders, pgGetPurchaseReturns, pgGetSettings, pgGetWarehouses } from "@/lib/postgres/data-access";
import type { InternalTransferDocument, MaterialMovementEntry, Warehouse } from "@/lib/types";
import { formatDateTimeStable } from "@/lib/formatters";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";

type MovementRow = MaterialMovementEntry & {
  referenceIdRaw?: string;
  referenceHref?: string;
  fromWarehouseName?: string;
  fromShelfName?: string;
  toWarehouseName?: string;
  toShelfName?: string;
};

export default async function MaterialMovementsPage({
  searchParams,
}: {
  searchParams?: Promise<{
    materialId?: string;
    sourceParentItemId?: string;
    referenceType?: string;
    direction?: string;
    fromWarehouse?: string;
    fromShelf?: string;
    toWarehouse?: string;
    toShelf?: string;
    referenceQuery?: string;
    noteQuery?: string;
    dateFrom?: string;
    dateTo?: string;
  }>;
}) {
  const session = await verifySession();
  const user = session.user;
  const locale = await getCurrentLocale();
  const t = getTranslations(locale);
  const tGlobal = t.Global ?? {};
  const tItemLists = t.ItemLists ?? {};

  if (!user || user.role !== 'admin') {
    return (
      <div className="text-center">
        <h1 className="text-2xl font-bold">{tGlobal.accessDenied}</h1>
        <p>{tGlobal.noPermission}</p>
      </div>
    );
  }

  const params = (await searchParams) || {};
  const selectedMaterialId = String(params.materialId || '').trim();
  const effectiveMaterialId = selectedMaterialId === 'all' ? '' : selectedMaterialId;
  const selectedSourceParentId = String(params.sourceParentItemId || '').trim();
  const effectiveSourceParentId = selectedSourceParentId === 'all' ? '' : selectedSourceParentId;
  const selectedReferenceType = String(params.referenceType || '').trim().toLowerCase();
  const selectedDirection = String(params.direction || '').trim().toLowerCase();
  const selectedFromWarehouse = String(params.fromWarehouse || '').trim();
  const selectedFromShelf = String(params.fromShelf || '').trim();
  const selectedToWarehouse = String(params.toWarehouse || '').trim();
  const selectedToShelf = String(params.toShelf || '').trim();
  const selectedReferenceQuery = String(params.referenceQuery || '').trim();
  const selectedNoteQuery = String(params.noteQuery || '').trim();
  const selectedDateFrom = String(params.dateFrom || '').trim();
  const selectedDateTo = String(params.dateTo || '').trim();

  const materials = (await pgGetMaterials({ page: 1, pageSize: 5000 })).items as Array<{ id: string; name: string }>;
  const warehouses = (await pgGetWarehouses({ page: 1, pageSize: 5000 })).items as Warehouse[];
  const settings = await pgGetSettings();
  const transferDocuments: InternalTransferDocument[] = (await pgGetInternalTransfers({ page: 1, pageSize: 5000 })).items as InternalTransferDocument[];
  const purchaseOrders = (await pgGetPurchaseOrders({ page: 1, pageSize: 5000 })).items as Array<Record<string, unknown>>;
  const salesInvoices = (await pgGetInvoices({ page: 1, pageSize: 5000 })).items as Array<Record<string, unknown>>;
  const purchaseReturns = (await pgGetPurchaseReturns({ page: 1, pageSize: 5000 })).items as Array<Record<string, unknown>>;
  const transferDocById = new Map(
    transferDocuments.map((doc) => [String(doc.id || '').trim(), doc])
  );
  const purchaseOrderById = new Map(
    purchaseOrders.map((order) => [String(order.id || '').trim(), order])
  );
  const purchaseOrderByNumber = new Map(
    purchaseOrders.map((order) => [String(order.orderNumber || '').trim(), order])
  );
  const salesInvoiceById = new Map(
    salesInvoices.map((invoice) => [String(invoice.id || '').trim(), invoice])
  );
  const salesInvoiceByNumber = new Map(
    salesInvoices.map((invoice) => [String(invoice.invoiceNumber || '').trim(), invoice])
  );
  const purchaseReturnById = new Map(
    purchaseReturns.map((entry) => [String(entry.id || '').trim(), entry])
  );
  const purchaseReturnByNumber = new Map(
    purchaseReturns.map((entry) => [String(entry.returnNumber || '').trim(), entry])
  );
  const disassemblyRecords = Array.isArray((settings as any)?.disassemblyRecords)
    ? (((settings as any).disassemblyRecords as Array<Record<string, unknown>>).filter((entry) => entry && typeof entry === 'object'))
    : [];
  const disassemblyRecordById = new Map(disassemblyRecords.map((record) => [String(record.id || '').trim(), record]));
  const disassemblyParentOptions = Array.from(
    new Map(
      disassemblyRecords
        .map((record) => [String(record.parentItemId || '').trim(), String(record.parentItemName || record.parentItemId || '').trim()] as const)
        .filter(([id]) => id),
    ).entries(),
  )
    .map(([id, name]) => ({ id, name }))
    .sort((left, right) => String(left.name || '').localeCompare(String(right.name || ''), locale));

  const materialById = new Map(materials.map((material) => [String(material.id || '').trim(), material.name]));
  const warehouseById = new Map(warehouses.map((warehouse) => [String(warehouse.id || '').trim(), warehouse.name]));
  const shelfById = new Map<string, string>();
  warehouses.forEach((warehouse) => {
    (warehouse.shelves || []).forEach((shelf) => {
      shelfById.set(String(shelf.id || '').trim(), String(shelf.name || '').trim());
    });
  });

  const normalizeReferenceType = (type: string): MaterialMovementEntry['referenceType'] => {
    const normalized = String(type || '').trim().toLowerCase();
    if (normalized === 'purchase' || normalized === 'purchase_order') return 'purchase';
    if (normalized === 'sale' || normalized === 'sales_invoice') return 'sale';
    if (normalized === 'sale-return' || normalized === 'sales_return') return 'sale-return';
    if (normalized === 'purchase-return' || normalized === 'purchase_return') return 'purchase-return';
    if (normalized === 'purchase-return-cancel' || normalized === 'purchase_return_cancel') return 'purchase-return-cancel';
    if (normalized === 'disassembly') return 'disassembly';
    if (normalized === 'transfer-doc' || normalized === 'transfer_doc' || normalized === 'internal_transfer_doc'
      || normalized === 'transfer_document' || normalized === 'transfer_document_receipt'
      || normalized === 'transfer_document_nullified' || normalized === 'transfer_document_reversal') return 'transfer-doc';
    return 'transfer';
  };
  const effectiveReferenceType = selectedReferenceType && selectedReferenceType !== 'all'
    ? normalizeReferenceType(selectedReferenceType)
    : '';

  const movements: MovementRow[] = (((await pgGetInventoryMovements({ page: 1, pageSize: 10000 })).items || []) as Array<Record<string, unknown>>)
        .filter((movement) => {
          const materialId = String(movement.materialId || '').trim();
          const sourceParentItemId = String(movement.sourceParentItemId || '').trim();
          const referenceType = normalizeReferenceType(String(movement.referenceType || 'transfer'));

          const quantityIn = Number(movement.quantityIn || 0);
          const quantityOut = Number(movement.quantityOut || 0);
          if (quantityIn === 0 && quantityOut === 0) return false; // skip nullified/placeholder movements
          return (!effectiveMaterialId || materialId === effectiveMaterialId)
            && (!effectiveSourceParentId || sourceParentItemId === effectiveSourceParentId)
            && (!effectiveReferenceType || referenceType === effectiveReferenceType);
        })
        .map((movement, index) => {
          const materialId = String(movement.materialId || '').trim();
          const warehouseId = String(movement.warehouseId || '').trim();
          const shelfId = String(movement.shelfId || '').trim();
          const quantityIn = Number(movement.quantityIn || 0);
          const quantityOut = Number(movement.quantityOut || 0);
          const direction: MaterialMovementEntry['direction'] = quantityOut > 0 ? 'out' : 'in';
          const quantity = Math.abs(quantityOut > 0 ? quantityOut : quantityIn);
          const referenceType = normalizeReferenceType(String(movement.referenceType || 'transfer'));
          const referenceIdRaw = String(movement.referenceId || '').trim() || undefined;
          const sourceParentItemId = String(movement.sourceParentItemId || '').trim() || undefined;
          const sourceParentRecordId = String(movement.sourceParentRecordId || movement.referenceId || '').trim() || undefined;
          const linkedDisassemblyRecord = sourceParentRecordId ? disassemblyRecordById.get(sourceParentRecordId) : undefined;
          const linkedParentName = typeof linkedDisassemblyRecord?.parentItemName === 'string'
            ? linkedDisassemblyRecord.parentItemName
            : undefined;
          const linkedTransferDoc = referenceType === 'transfer-doc' && referenceIdRaw
            ? transferDocById.get(referenceIdRaw)
            : undefined;
          const linkedPurchaseOrder = referenceType === 'purchase' && referenceIdRaw
            ? purchaseOrderById.get(referenceIdRaw)
            : undefined;
          const linkedSalesInvoice = (referenceType === 'sale' || referenceType === 'sale-return') && referenceIdRaw
            ? salesInvoiceById.get(referenceIdRaw)
            : undefined;
          const linkedPurchaseReturn = (referenceType === 'purchase-return' || referenceType === 'purchase-return-cancel') && referenceIdRaw
            ? purchaseReturnById.get(referenceIdRaw)
            : undefined;
          const referenceHref = linkedTransferDoc
            ? `/admin/data/internal-transfers/${encodeURIComponent(referenceIdRaw || linkedTransferDoc.id)}`
            : linkedPurchaseOrder
              ? `/admin/purchases/view/${encodeURIComponent(String(linkedPurchaseOrder.id || referenceIdRaw))}`
              : linkedSalesInvoice
                ? `/admin/sales/view/${encodeURIComponent(String(linkedSalesInvoice.id || referenceIdRaw))}`
                : linkedPurchaseReturn
                  ? `/admin/purchases/returns/${encodeURIComponent(String(linkedPurchaseReturn.id || referenceIdRaw))}`
              : undefined;

          return {
            id: String(movement.id || `pg-movement-${index + 1}`),
            date: String(movement.date || movement.movementDate || ''),
            materialId,
            materialName: materialById.get(materialId) || materialId,
            referenceType,
            referenceNumber: referenceType === 'disassembly'
              ? String(linkedDisassemblyRecord?.recordNumber || movement.referenceId || movement.id || '-')
              : linkedTransferDoc
                ? String(linkedTransferDoc.transferNumber || linkedTransferDoc.id || movement.referenceId || movement.id || '-')
              : linkedPurchaseOrder
                ? String(linkedPurchaseOrder.orderNumber || linkedPurchaseOrder.id || movement.referenceId || movement.id || '-')
              : linkedSalesInvoice
                ? String(linkedSalesInvoice.invoiceNumber || linkedSalesInvoice.id || movement.referenceId || movement.id || '-')
              : linkedPurchaseReturn
                ? String(linkedPurchaseReturn.returnNumber || linkedPurchaseReturn.id || movement.referenceId || movement.id || '-')
              : String(movement.referenceId || movement.invoiceId || movement.shipmentId || movement.id || '-'),
            referenceIdRaw,
            referenceHref,
            direction,
            quantity,
            warehouseId: warehouseId || undefined,
            warehouseName: warehouseId ? (warehouseById.get(warehouseId) || warehouseId) : undefined,
            shelfId: shelfId || undefined,
            shelfName: shelfId ? (shelfById.get(shelfId) || shelfId) : undefined,
            note: typeof movement.note === 'string' ? movement.note : undefined,
            sourceParentItemId,
            sourceParentItemName: sourceParentItemId ? (materialById.get(sourceParentItemId) || linkedParentName || sourceParentItemId) : undefined,
            sourceParentRecordId,
          };
        });

  const joinUniqueLabels = (values: Array<string | undefined>) => {
    const normalized = Array.from(new Set(values.map((value) => String(value || '').trim()).filter(Boolean)));
    return normalized.join('، ');
  };

  const movementsWithFlow: MovementRow[] = movements.map((movement, index) => {
    let fromWarehouseName = movement.direction === 'out' ? movement.warehouseName : undefined;
    let fromShelfName = movement.direction === 'out' ? movement.shelfName : undefined;
    let toWarehouseName = movement.direction === 'in' ? movement.warehouseName : undefined;
    let toShelfName = movement.direction === 'in' ? movement.shelfName : undefined;

    // Pair opposite entries of the same transfer to infer missing side.
    const counterparts = movements.filter((candidate, candidateIndex) => {
      if (candidateIndex === index) return false;
      if (candidate.materialId !== movement.materialId) return false;
      if (candidate.referenceType !== movement.referenceType) return false;
      if (candidate.referenceNumber !== movement.referenceNumber) return false;
      return candidate.direction !== movement.direction;
    });

    const matchedCounterpart = counterparts.find((candidate) => Math.abs(Number(candidate.quantity || 0) - Number(movement.quantity || 0)) < 0.0001)
      || counterparts[0];

    if (matchedCounterpart) {
      if (!fromWarehouseName) fromWarehouseName = matchedCounterpart.warehouseName;
      if (!fromShelfName) fromShelfName = matchedCounterpart.shelfName;
      if (!toWarehouseName) toWarehouseName = matchedCounterpart.warehouseName;
      if (!toShelfName) toShelfName = matchedCounterpart.shelfName;
    }

    // For transfer documents, enrich with document-level source/target shelves when available.
    if (movement.referenceType === 'transfer-doc' && movement.referenceIdRaw) {
      const doc = transferDocById.get(movement.referenceIdRaw);
      if (doc) {
        const targetLines = (doc.items || []).filter((item) => String(item.materialId || '').trim() === String(movement.materialId || '').trim());
        if (targetLines.length > 0) {
          const sourceWarehouseLabel = joinUniqueLabels(targetLines.map((item) => warehouseById.get(String(item.fromWarehouseId || '').trim()) || String(item.fromWarehouseId || '').trim()));
          const sourceShelfLabel = joinUniqueLabels(targetLines.map((item) => shelfById.get(String(item.fromShelfId || '').trim()) || String(item.fromShelfId || '').trim()));
          const targetWarehouseLabel = joinUniqueLabels(targetLines.map((item) => {
            const warehouseId = doc.enableWarehouseTransfer ? String(item.toWarehouseId || '').trim() : String(item.fromWarehouseId || '').trim();
            return warehouseById.get(warehouseId) || warehouseId;
          }));
          const targetShelfLabel = joinUniqueLabels(targetLines.flatMap((item) => {
            const distributions = Array.isArray(item.receiptDistributions)
              ? item.receiptDistributions
                  .map((entry) => String(entry?.shelfId || '').trim())
                  .filter(Boolean)
              : [];
            if (distributions.length > 0 && String(doc.receiptStatus || 'pending') !== 'pending') {
              return distributions.map((shelfId) => shelfById.get(shelfId) || shelfId);
            }
            const shelfId = doc.enableShelfTransfer ? String(item.toShelfId || '').trim() : String(item.fromShelfId || '').trim();
            return [shelfById.get(shelfId) || shelfId];
          }));

          // For transfer-doc rows, always trust the document's source/target definition
          // over inferred movement pairing when labels are available.
          if (sourceWarehouseLabel) fromWarehouseName = sourceWarehouseLabel;
          if (sourceShelfLabel) fromShelfName = sourceShelfLabel;
          if (targetWarehouseLabel) toWarehouseName = targetWarehouseLabel;
          if (targetShelfLabel) toShelfName = targetShelfLabel;
        }
      }
    }

    return {
      ...movement,
      fromWarehouseName,
      fromShelfName,
      toWarehouseName,
      toShelfName,
    };
  });

  const directionFilter = selectedDirection === 'all' ? '' : selectedDirection;
  const fromWarehouseFilter = selectedFromWarehouse === 'all' ? '' : selectedFromWarehouse;
  const fromShelfFilter = selectedFromShelf === 'all' ? '' : selectedFromShelf;
  const toWarehouseFilter = selectedToWarehouse === 'all' ? '' : selectedToWarehouse;
  const toShelfFilter = selectedToShelf === 'all' ? '' : selectedToShelf;
  const referenceQueryFilter = selectedReferenceQuery.toLowerCase();
  const noteQueryFilter = selectedNoteQuery.toLowerCase();

  const uniqueSorted = (values: Array<string | undefined>) =>
    Array.from(new Set(values.map((value) => String(value || '').trim()).filter(Boolean)))
      .sort((left, right) => left.localeCompare(right, locale));

  const fromWarehouseOptions = uniqueSorted(movementsWithFlow.map((movement) => movement.fromWarehouseName));
  const fromShelfOptions = uniqueSorted(movementsWithFlow.map((movement) => movement.fromShelfName));
  const toWarehouseOptions = uniqueSorted(movementsWithFlow.map((movement) => movement.toWarehouseName));
  const toShelfOptions = uniqueSorted(movementsWithFlow.map((movement) => movement.toShelfName));

  const filteredMovements = movementsWithFlow.filter((movement) => {
    if (directionFilter && movement.direction !== directionFilter) return false;
    if (fromWarehouseFilter && String(movement.fromWarehouseName || '').trim() !== fromWarehouseFilter) return false;
    if (fromShelfFilter && String(movement.fromShelfName || '').trim() !== fromShelfFilter) return false;
    if (toWarehouseFilter && String(movement.toWarehouseName || '').trim() !== toWarehouseFilter) return false;
    if (toShelfFilter && String(movement.toShelfName || '').trim() !== toShelfFilter) return false;

    if (referenceQueryFilter) {
      const referenceText = String(movement.referenceNumber || '').toLowerCase();
      if (!referenceText.includes(referenceQueryFilter)) return false;
    }

    if (noteQueryFilter) {
      const noteText = String(movement.note || '').toLowerCase();
      if (!noteText.includes(noteQueryFilter)) return false;
    }

    const movementDate = movement.date ? new Date(movement.date) : undefined;
    if (selectedDateFrom) {
      const fromDate = new Date(`${selectedDateFrom}T00:00:00.000Z`);
      if (!movementDate || Number.isNaN(movementDate.getTime()) || movementDate < fromDate) return false;
    }
    if (selectedDateTo) {
      const toDate = new Date(`${selectedDateTo}T23:59:59.999Z`);
      if (!movementDate || Number.isNaN(movementDate.getTime()) || movementDate > toDate) return false;
    }

    return true;
  });

  const movementTypeLabel = (type: string) => {
    if (type === 'purchase') return tItemLists.movementTypePurchase ?? 'مشتريات';
    if (type === 'sale') return tItemLists.movementTypeSale ?? 'مبيعات';
    if (type === 'sale-return') return tItemLists.movementTypeSaleReturn ?? 'مردود مبيعات';
    if (type === 'purchase-return') return tItemLists.movementTypePurchaseReturn ?? 'مردود مشتريات';
    if (type === 'purchase-return-cancel') return tItemLists.movementTypePurchaseReturnCancel ?? 'إلغاء مردود مشتريات';
    if (type === 'disassembly') return tItemLists.disassemblyPageTitle ?? 'تفكيك';
    if (type === 'transfer') return tItemLists.movementTypeTransfer ?? 'تحويل داخلي';
    if (type === 'transfer-doc') return tItemLists.movementTypeTransferDoc ?? 'مستند تحويل';
    return type;
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>{tItemLists.materialMovementTitle ?? 'تقرير حركة الصنف'}</CardTitle>
        <CardDescription>{tItemLists.materialMovementDescription ?? 'عرض كل حركات دخول وخروج الصنف حسب المستودع والرف.'}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="rounded-lg border bg-muted/20 p-4">
          <form method="get" className="grid gap-3 xl:grid-cols-6 lg:grid-cols-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label>{tItemLists.dateFromLabel ?? 'التاريخ من'}</Label>
              <input
                type="date"
                name="dateFrom"
                defaultValue={selectedDateFrom}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              />
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.dateToLabel ?? 'التاريخ إلى'}</Label>
              <input
                type="date"
                name="dateTo"
                defaultValue={selectedDateTo}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              />
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.itemNameLabel ?? 'اسم الصنف'}</Label>
              <select
                name="materialId"
                defaultValue={effectiveMaterialId || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allItemsOption ?? 'كل الأصناف'}</option>
                {materials.map((material) => (
                  <option key={material.id} value={material.id}>{material.name}</option>
                ))}
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.movementDirectionLabel ?? 'الاتجاه'}</Label>
              <select
                name="direction"
                defaultValue={directionFilter || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allDirectionsOption ?? 'كل الاتجاهات'}</option>
                <option value="in">{tItemLists.directionIn ?? 'دخول'}</option>
                <option value="out">{tItemLists.directionOut ?? 'خروج'}</option>
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.parentItemLabel ?? 'الصنف الأب / المصدر'}</Label>
              <select
                name="sourceParentItemId"
                defaultValue={effectiveSourceParentId || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allItemsOption ?? 'كل الأصناف'}</option>
                {disassemblyParentOptions.map((parent) => (
                  <option key={parent.id} value={parent.id}>{parent.name}</option>
                ))}
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.movementTypeLabel ?? 'نوع الحركة'}</Label>
              <select
                name="referenceType"
                defaultValue={effectiveReferenceType || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.filterAllMovements ?? 'كل الحركات'}</option>
                <option value="disassembly">{tItemLists.disassemblyPageTitle ?? 'تفكيك'}</option>
                <option value="purchase">{tItemLists.movementTypePurchase ?? 'مشتريات'}</option>
                <option value="sale">{tItemLists.movementTypeSale ?? 'مبيعات'}</option>
                <option value="transfer">{tItemLists.movementTypeTransfer ?? 'تحويل داخلي'}</option>
                <option value="transfer-doc">{tItemLists.movementTypeTransferDoc ?? 'مستند تحويل'}</option>
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.fromWarehouseLabel ?? 'من مستودع'}</Label>
              <select
                name="fromWarehouse"
                defaultValue={fromWarehouseFilter || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allOption ?? 'الكل'}</option>
                {fromWarehouseOptions.map((name) => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.fromShelfLabel ?? 'من رف'}</Label>
              <select
                name="fromShelf"
                defaultValue={fromShelfFilter || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allOption ?? 'الكل'}</option>
                {fromShelfOptions.map((name) => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.toWarehouseLabel ?? 'إلى مستودع'}</Label>
              <select
                name="toWarehouse"
                defaultValue={toWarehouseFilter || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allOption ?? 'الكل'}</option>
                {toWarehouseOptions.map((name) => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.toShelfLabel ?? 'إلى رف'}</Label>
              <select
                name="toShelf"
                defaultValue={toShelfFilter || 'all'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              >
                <option value="all">{tItemLists.allOption ?? 'الكل'}</option>
                {toShelfOptions.map((name) => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </select>
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.referenceLabel ?? 'المرجع'}</Label>
              <input
                type="text"
                name="referenceQuery"
                defaultValue={selectedReferenceQuery}
                placeholder={tItemLists.referenceSearchPlaceholder ?? 'ابحث في المرجع'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              />
            </div>

            <div className="grid gap-2">
              <Label>{tItemLists.notesLabel ?? 'ملاحظة'}</Label>
              <input
                type="text"
                name="noteQuery"
                defaultValue={selectedNoteQuery}
                placeholder={tItemLists.noteSearchPlaceholder ?? 'ابحث في الملاحظة'}
                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background"
              />
            </div>

            <div className="flex items-end gap-2">
              <Button type="submit" variant="outline" className="w-fit">
                {tItemLists.filterMovementsButton ?? 'تصفية'}
              </Button>
              <Button asChild variant="ghost" className="w-fit">
                <Link href="/admin/data/material-movements">{tItemLists.resetFiltersButton ?? 'إعادة ضبط'}</Link>
              </Button>
            </div>
          </form>
        </div>

        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{tItemLists.movementDateLabel ?? 'التاريخ'}</TableHead>
                <TableHead>{tItemLists.itemNameLabel ?? 'الصنف'}</TableHead>
                <TableHead>{tItemLists.movementTypeLabel ?? 'نوع الحركة'}</TableHead>
                <TableHead>{tItemLists.movementDirectionLabel ?? 'الاتجاه'}</TableHead>
                <TableHead>{tItemLists.quantityLabel ?? 'الكمية'}</TableHead>
                <TableHead>{tItemLists.fromWarehouseLabel ?? 'من مستودع'}</TableHead>
                <TableHead>{tItemLists.fromShelfLabel ?? 'من رف'}</TableHead>
                <TableHead>{tItemLists.toWarehouseLabel ?? 'إلى مستودع'}</TableHead>
                <TableHead>{tItemLists.toShelfLabel ?? 'إلى رف'}</TableHead>
                <TableHead>{tItemLists.referenceLabel ?? 'المرجع'}</TableHead>
                <TableHead>{tItemLists.parentItemLabel ?? 'الصنف الأب / المصدر'}</TableHead>
                <TableHead>{tItemLists.notesLabel ?? 'ملاحظة'}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredMovements.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={12} className="text-center text-muted-foreground h-24">
                    {tItemLists.noMovementsFound ?? 'لا توجد حركات للصنف المحدد.'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredMovements.map((movement, index) => (
                  <TableRow key={`${movement.id}-${movement.referenceType}-${movement.referenceNumber}-${movement.direction}-${movement.warehouseId || ''}-${movement.shelfId || ''}-${index}`}>
                    <TableCell>{formatDateTimeStable(movement.date)}</TableCell>
                    <TableCell>{movement.materialName}</TableCell>
                    <TableCell>{movementTypeLabel(movement.referenceType)}</TableCell>
                    <TableCell>{movement.direction === 'in' ? (tItemLists.directionIn ?? 'دخول') : (tItemLists.directionOut ?? 'خروج')}</TableCell>
                    <TableCell>{movement.quantity}</TableCell>
                    <TableCell>{movement.fromWarehouseName || '-'}</TableCell>
                    <TableCell>{movement.fromShelfName || '-'}</TableCell>
                    <TableCell>{movement.toWarehouseName || '-'}</TableCell>
                    <TableCell>{movement.toShelfName || '-'}</TableCell>
                    <TableCell>
                      {movement.referenceHref ? (
                        <Link href={movement.referenceHref} className="text-primary underline-offset-2 hover:underline">
                          {movement.referenceNumber}
                        </Link>
                      ) : (
                        <span>{movement.referenceNumber}</span>
                      )}
                    </TableCell>
                    <TableCell>{movement.sourceParentItemName || '-'}</TableCell>
                    <TableCell>{movement.note || '-'}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
