"use client";

import React, { useState, useEffect, useRef } from "react";
import { useRouter, useParams } from "next/navigation";
import {
  MdQrCodeScanner,
  MdInfo,
  MdCheckCircle,
  MdWarning,
  MdSearch,
  MdFilter,
  MdFilterList,
  MdFlashlightOn,
  MdFlashlightOff,
  MdExpandMore,
  MdExpandLess,
  MdReportProblem,
  MdRemoveCircleOutline,
} from "react-icons/md";
import { FiCamera, FiRefreshCw } from "react-icons/fi";
import BarcodeScanner from "@/components/ui/BarcodeScanner";
import MarkDamageModal from "../../../../../../components/ui/MarkDamageModal";
import ConfirmationModal from "@/components/ui/ConfirmationModal";
import { warehouseShipmentService } from "@/services/api";
import { Shipment, ShipmentStatus } from "@/types/shipment";
import { PalletReceivedCondition } from "@/types/pallet";
import { formatDateTime } from "@/utils/dateUtils";
import { playScannerSound, initializeAudioContext } from "@/utils/soundUtils";
import { barcodeToastManager } from "@/utils/barcodeToastManager";

export default function ScanShipmentPage() {
  const router = useRouter();
  const params = useParams();
  const shipmentId = Number(params.id);
  const filterDropdownRef = useRef<HTMLDivElement>(null);

  const [shipment, setShipment] = useState<Shipment | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [scannedPallets, setScannedPallets] = useState<string[]>([]);
  const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  const [searchPallet, setSearchPallet] = useState("");
  const [searchFilter, setSearchFilter] = useState<
    "palletNumber" | "barcode" | "orderId"
  >("palletNumber");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [expandedPallets, setExpandedPallets] = useState<Set<number>>(
    new Set()
  );

  // Modal states
  const [isPalletDamageModalOpen, setIsPalletDamageModalOpen] = useState(false);
  const [selectedPalletForDamage, setSelectedPalletForDamage] = useState<{
    shipmentPalletId: number;
    palletNumber: number;
    palletBarcode: string;
    isEdit: boolean;
    description: string;
    images: string[];
  } | null>(null);
  const [palletToMarkMissing, setPalletToMarkMissing] = useState<{
    shipmentPalletId: number;
    palletNumber: number;
  } | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isMarkCompleteModalOpen, setIsMarkCompleteModalOpen] = useState(false);
  const [isMarkingComplete, setIsMarkingComplete] = useState(false);
  const [unscannedBarcodesInfo, setUnscannedBarcodesInfo] = useState<{
    unscannedCount: number;
    totalCount: number;
    unscannedItems: Array<{ barcode: string; productName: string }>;
  } | null>(null);

  // Barcode processing state
  const [isProcessing, setIsProcessing] = useState(false);

  // Helper function to determine if current viewport is mobile
  const isMobileViewport = () => window.innerWidth < 1024;

  useEffect(() => {
    const fetchShipment = async () => {
      try {
        setLoading(true);
        const response = await warehouseShipmentService.getShipment(shipmentId);
        const shipmentData = response.data;

        // Check if shipment is dispatched
        if (shipmentData.status !== ShipmentStatus.DISPATCHED) {
          setError(
            "This shipment is not available for scanning. Only dispatched shipments can be scanned."
          );
          return;
        }

        setShipment(shipmentData);

        // Calculate scan progress
        const totalPallets = shipmentData.shipmentPallets?.length || 0;
        const scannedPalletsData =
          shipmentData.shipmentPallets?.filter(
            (sp: any) => sp.receiverScannedAt
          ) || [];

        setScanProgress({
          scanned: scannedPalletsData.length,
          total: totalPallets,
        });

        // Set already scanned pallets
        setScannedPallets(
          scannedPalletsData.map((sp: any) => sp.pallet?.barcode?.code || "")
        );

        setError(null);
      } catch (err) {
        console.error("Failed to fetch shipment:", err);
        setError("Failed to load shipment details. Please try again.");
      } finally {
        setLoading(false);
      }
    };

    if (shipmentId) {
      fetchShipment();
    }
  }, [shipmentId]);

  // Close filter dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        filterDropdownRef.current &&
        !filterDropdownRef.current.contains(event.target as Node)
      ) {
        setIsFilterOpen(false);
      }
    };

    if (isFilterOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isFilterOpen]);

  // Handle barcode detection from common scanner
  const handleBarcodeDetected = async (barcode: string) => {
    if (isProcessing) return; // Prevent multiple scans

    setIsProcessing(true);

    try {
      // Process the barcode
      await processBarcodeInput(barcode);
    } catch (error: any) {
      console.error("Error processing barcode:", error);
    } finally {
      // Add a small delay before enabling processing again to prevent rapid retriggers
      setTimeout(() => {
        setIsProcessing(false);
      }, 500);
    }
  };

  // Extract barcode processing logic
  const processBarcodeInput = async (barcodeValue: string) => {
    if (!barcodeValue.trim()) {
      barcodeToastManager.addErrorToast("Please enter a barcode to scan");
      return;
    }

    try {
      // Call API to scan pallet barcode and update database
      const response = await warehouseShipmentService.scanPallet(
        shipmentId,
        barcodeValue.trim()
      );
      const updatedShipment = response.data;

      // Update local state with fresh data from API
      setShipment(updatedShipment);

      // Recalculate scan progress
      const totalPallets = updatedShipment.shipmentPallets?.length || 0;
      const scannedPalletsData =
        updatedShipment.shipmentPallets?.filter(
          (sp: any) => sp.receiverScannedAt
        ) || [];

      setScanProgress({
        scanned: scannedPalletsData.length,
        total: totalPallets,
      });

      // Update scanned pallets list
      setScannedPallets(
        scannedPalletsData.map((sp: any) => sp.pallet?.barcode?.code || "")
      );

      barcodeToastManager.addSuccessToast("Pallet scanned successfully!");

      // Sound already played when barcode was detected

      // Check if all pallets are scanned
      if (scannedPalletsData.length === totalPallets) {
        barcodeToastManager.addSuccessToast("All pallets have been scanned!");
      }
    } catch (error: any) {
      console.error("Failed to scan barcode:", error);
      const errorMessage =
        error.response?.data?.message ||
        "Failed to scan barcode. Please try again.";

      // Show toast error but don't throw for duplicate/already scanned barcodes
      barcodeToastManager.addErrorToast(errorMessage);

      // Only re-throw for serious errors that should stop the scanner
      // Don't re-throw for duplicate scans or barcode-not-found errors
      const shouldStopScanner =
        !error.response?.status ||
        (error.response.status !== 400 &&
          error.response.status !== 404 &&
          error.response.status !== 409);

      if (shouldStopScanner) {
        throw error;
      }
    }
  };

  const handleRemoveScan = async (barcodeCode: string) => {
    try {
      const response = await warehouseShipmentService.removePalletScan(
        shipmentId,
        barcodeCode
      );
      const updatedShipment = response.data;

      // Update local state with fresh data from API
      setShipment(updatedShipment);

      // Recalculate scan progress
      const totalPallets = updatedShipment.shipmentPallets?.length || 0;
      const scannedPalletsData =
        updatedShipment.shipmentPallets?.filter(
          (sp: any) => sp.receiverScannedAt
        ) || [];

      setScanProgress({
        scanned: scannedPalletsData.length,
        total: totalPallets,
      });

      // Update scanned pallets list
      setScannedPallets(
        scannedPalletsData.map((sp: any) => sp.pallet?.barcode?.code || "")
      );

      barcodeToastManager.addSuccessToast("Pallet scan removed successfully!");
    } catch (error: any) {
      console.error("Failed to remove scan:", error);
      const errorMessage =
        error.response?.data?.message ||
        "Failed to remove scan. Please try again.";
      barcodeToastManager.addErrorToast(errorMessage);
    }
  };

  const openPalletDamageModal = (shipmentPallet: any) => {
    const isEdit =
      shipmentPallet.receivedCondition === PalletReceivedCondition.DAMAGED;
    setSelectedPalletForDamage({
      shipmentPalletId: shipmentPallet.id,
      palletNumber: shipmentPallet.palletNumber,
      palletBarcode: shipmentPallet.pallet?.barcode?.code || "",
      isEdit,
      description: isEdit ? shipmentPallet.conditionDescription || "" : "",
      images: isEdit ? shipmentPallet.conditionImages || [] : [],
    });
    setIsPalletDamageModalOpen(true);
  };

  const handlePalletDamageSubmit = async (
    description: string,
    images: string[]
  ) => {
    if (!selectedPalletForDamage) return;

    try {
      setIsSubmitting(true);

      const response = await warehouseShipmentService.markPalletDamaged(
        shipmentId,
        selectedPalletForDamage.shipmentPalletId,
        description,
        images
      );

      setShipment(response.data);
      refreshScanProgressFromShipment(response.data);

      barcodeToastManager.addSuccessToast(
        selectedPalletForDamage.isEdit
          ? "Damage report updated successfully!"
          : "Pallet marked as damaged successfully!"
      );
      setIsPalletDamageModalOpen(false);
      setSelectedPalletForDamage(null);
    } catch (error: any) {
      console.error("Failed to mark pallet damaged:", error);
      const errorMessage =
        error.response?.data?.message ||
        "Failed to mark pallet damaged. Please try again.";
      barcodeToastManager.addErrorToast(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handlePalletDamageModalClose = () => {
    setIsPalletDamageModalOpen(false);
    setSelectedPalletForDamage(null);
  };

  const handleConfirmMarkMissing = async () => {
    if (!palletToMarkMissing) return;

    try {
      const response = await warehouseShipmentService.markPalletMissing(
        shipmentId,
        palletToMarkMissing.shipmentPalletId
      );
      setShipment(response.data);
      refreshScanProgressFromShipment(response.data);
      barcodeToastManager.addSuccessToast(
        `Pallet #${palletToMarkMissing.palletNumber} marked as missing.`
      );
    } catch (error: any) {
      console.error("Failed to mark pallet missing:", error);
      barcodeToastManager.addErrorToast(
        error.response?.data?.message ||
          "Failed to mark pallet missing. Please try again."
      );
    } finally {
      setPalletToMarkMissing(null);
    }
  };

  const handleClearPalletCondition = async (
    shipmentPalletId: number,
    palletNumber: number,
    fromCondition: PalletReceivedCondition
  ) => {
    try {
      const response = await warehouseShipmentService.clearPalletCondition(
        shipmentId,
        shipmentPalletId
      );
      setShipment(response.data);
      refreshScanProgressFromShipment(response.data);
      barcodeToastManager.addSuccessToast(
        fromCondition === PalletReceivedCondition.DAMAGED
          ? `Pallet #${palletNumber} marked as not damaged.`
          : `Pallet #${palletNumber} reset.`
      );
    } catch (error: any) {
      console.error("Failed to clear pallet condition:", error);
      barcodeToastManager.addErrorToast(
        error.response?.data?.message ||
          "Failed to update pallet. Please try again."
      );
    }
  };

  const refreshScanProgressFromShipment = (updatedShipment: any) => {
    const totalPallets = updatedShipment.shipmentPallets?.length || 0;
    const scannedPalletsData =
      updatedShipment.shipmentPallets?.filter(
        (sp: any) => sp.receiverScannedAt
      ) || [];
    setScanProgress({ scanned: scannedPalletsData.length, total: totalPallets });
    setScannedPallets(
      scannedPalletsData.map((sp: any) => sp.pallet?.barcode?.code || "")
    );
  };

  const handleMarkComplete = async (forceComplete: boolean = false) => {
    try {
      setIsMarkingComplete(true);

      const response = await warehouseShipmentService.markComplete(
        shipmentId,
        forceComplete
      );

      barcodeToastManager.addSuccessToast(
        "Shipment marked as completed successfully!"
      );

      // Navigate back to shipments list after successful completion
      router.push("/warehouses/shipments");
    } catch (error: any) {
      console.error("Failed to mark shipment as complete:", error);

      // Check if this is an unscanned barcodes warning
      if (error.response?.data?.requiresConfirmation) {
        const errorData = error.response.data;
        setUnscannedBarcodesInfo({
          unscannedCount: errorData.unscannedCount,
          totalCount: errorData.totalCount,
          unscannedItems: errorData.unscannedItems || [],
        });
        setIsMarkCompleteModalOpen(false); // Close the regular modal
        return; // Don't show error toast, show confirmation modal instead
      }

      const errorMessage =
        error.response?.data?.message ||
        "Failed to mark shipment as complete. Please try again.";
      barcodeToastManager.addErrorToast(errorMessage);
    } finally {
      setIsMarkingComplete(false);
      if (!unscannedBarcodesInfo) {
        setIsMarkCompleteModalOpen(false);
      }
    }
  };

  const handleForceComplete = async () => {
    setUnscannedBarcodesInfo(null); // Close the unscanned barcodes modal
    await handleMarkComplete(true); // Force complete
  };

  const togglePalletExpansion = (palletId: number) => {
    setExpandedPallets((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(palletId)) {
        newSet.delete(palletId);
      } else {
        newSet.add(palletId);
      }
      return newSet;
    });
  };

  // Sort: pending first (still need action), then ok, then damaged, then missing.
  const getSortedPallets = (pallets: any[]) => {
    const order: Record<string, number> = {
      [PalletReceivedCondition.PENDING]: 0,
      [PalletReceivedCondition.OK]: 1,
      [PalletReceivedCondition.DAMAGED]: 2,
      [PalletReceivedCondition.MISSING]: 3,
    };
    return [...pallets].sort((a, b) => {
      const aOrder = order[a.receivedCondition] ?? 0;
      const bOrder = order[b.receivedCondition] ?? 0;
      if (aOrder !== bOrder) return aOrder - bOrder;
      return (a.palletNumber ?? 0) - (b.palletNumber ?? 0);
    });
  };

  const getConditionStyles = (condition: PalletReceivedCondition) => {
    switch (condition) {
      case PalletReceivedCondition.OK:
        return { label: "Scanned", badgeClass: "bg-green-100 text-green-800" };
      case PalletReceivedCondition.DAMAGED:
        return { label: "Damaged", badgeClass: "bg-amber-100 text-amber-800" };
      case PalletReceivedCondition.MISSING:
        return { label: "Missing", badgeClass: "bg-red-100 text-red-800" };
      case PalletReceivedCondition.PENDING:
      default:
        return { label: "Unscanned", badgeClass: "bg-gray-200 text-gray-700" };
    }
  };

  const renderPalletCard = (shipmentPallet: any, isMobile: boolean) => {
    const isExpanded = expandedPallets.has(shipmentPallet.id);
    const condition: PalletReceivedCondition =
      shipmentPallet.receivedCondition || PalletReceivedCondition.PENDING;
    const conditionStyles = getConditionStyles(condition);
    const palletBarcode = shipmentPallet.pallet?.barcode?.code || "";

    // Group products by name for the expanded view
    const productGroups: {
      [key: string]: { barcodes: string[]; quantity: number };
    } = {};
    shipmentPallet.shipmentPalletItems?.forEach((item: any) => {
      const productName =
        item.barcode?.purchaseOrderItem?.product?.name || "Unknown Product";
      const code = item.barcode?.code || "";
      if (!productGroups[productName]) {
        productGroups[productName] = { barcodes: [], quantity: 0 };
      }
      productGroups[productName].barcodes.push(code);
      productGroups[productName].quantity += 1;
    });

    return (
      <div
        key={shipmentPallet.id}
        className="bg-gray-50 rounded-lg border border-gray-200"
      >
        <div
          className="p-4 cursor-pointer hover:bg-gray-100 transition-colors"
          onClick={() => togglePalletExpansion(shipmentPallet.id)}
        >
          <div className="grid grid-cols-[1fr_auto] gap-4 items-center">
            <div className="space-y-1">
              <div className="flex items-center flex-wrap gap-2">
                <div className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">
                  Pallet #{shipmentPallet.palletNumber}
                </div>
                <div
                  className={`px-2 py-0.5 rounded-full text-xs font-medium ${conditionStyles.badgeClass}`}
                >
                  {conditionStyles.label}
                </div>
                <div className="text-sm text-gray-500">
                  {shipmentPallet.shipmentPalletItems?.length || 0} items
                </div>
              </div>
              {palletBarcode && (
                <div className="text-sm text-gray-600">
                  Barcode: {palletBarcode}
                </div>
              )}
              {condition === PalletReceivedCondition.DAMAGED &&
                shipmentPallet.conditionDescription && (
                  <div className="text-xs text-amber-700 mt-1 line-clamp-2">
                    {shipmentPallet.conditionDescription}
                  </div>
                )}
            </div>

            <div className="flex items-center space-x-2">
              {condition === PalletReceivedCondition.PENDING && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    setPalletToMarkMissing({
                      shipmentPalletId: shipmentPallet.id,
                      palletNumber: shipmentPallet.palletNumber,
                    });
                  }}
                  className="flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 hover:bg-red-50 rounded transition-colors"
                >
                  <MdRemoveCircleOutline size={14} />
                  Missing
                </button>
              )}
              {condition === PalletReceivedCondition.OK && (
                <>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      openPalletDamageModal(shipmentPallet);
                    }}
                    className="flex items-center gap-1 px-2 py-1 text-xs text-amber-700 hover:text-amber-900 hover:bg-amber-50 rounded transition-colors"
                  >
                    <MdReportProblem size={14} />
                    Mark Damaged
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRemoveScan(palletBarcode);
                    }}
                    className="px-2 py-1 text-xs text-red-600 hover:text-red-800 hover:bg-red-50 rounded transition-colors"
                  >
                    Remove Scan
                  </button>
                </>
              )}
              {condition === PalletReceivedCondition.DAMAGED && (
                <>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      openPalletDamageModal(shipmentPallet);
                    }}
                    className="px-2 py-1 text-xs text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded transition-colors"
                  >
                    Edit Report
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleClearPalletCondition(
                        shipmentPallet.id,
                        shipmentPallet.palletNumber,
                        PalletReceivedCondition.DAMAGED
                      );
                    }}
                    className="px-2 py-1 text-xs text-green-700 hover:text-green-900 hover:bg-green-50 rounded transition-colors"
                  >
                    Not Damaged
                  </button>
                </>
              )}
              {condition === PalletReceivedCondition.MISSING && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleClearPalletCondition(
                      shipmentPallet.id,
                      shipmentPallet.palletNumber,
                      PalletReceivedCondition.MISSING
                    );
                  }}
                  className="px-2 py-1 text-xs text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded transition-colors"
                >
                  Reset
                </button>
              )}
              <div className="flex items-center">
                {isExpanded ? (
                  <MdExpandLess className="text-gray-500" size={20} />
                ) : (
                  <MdExpandMore className="text-gray-500" size={20} />
                )}
              </div>
            </div>
          </div>
        </div>

        {isExpanded && (
          <div className="px-4 pb-4">
            <div className="space-y-3">
              {Object.entries(productGroups).map(([productName, group]) => (
                <div
                  key={productName}
                  className="bg-white rounded-md border border-gray-200 p-3"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <h5 className="text-sm font-medium text-gray-900">
                        {productName}
                      </h5>
                      <div className="text-xs text-gray-500 mt-1">
                        Barcodes: {group.barcodes.join(", ")}
                      </div>
                    </div>
                    <div className="text-sm font-medium text-blue-600 bg-blue-50 px-2 py-1 rounded">
                      x {group.quantity}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-100 text-red-700 p-4 rounded-md">
        <p className="font-medium">Error</p>
        <p>{error}</p>
        <button
          onClick={() => router.back()}
          className="mt-4 bg-white text-red-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back
        </button>
      </div>
    );
  }

  if (!shipment) {
    return (
      <div className="text-center py-12">
        <MdInfo className="mx-auto mb-4 text-48 text-gray-500" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">
          Shipment not found
        </h3>
        <p className="text-gray-500">
          The shipment you're looking for doesn't exist or you don't have access
          to it.
        </p>
      </div>
    );
  }

  const progressPercentage =
    scanProgress.total > 0
      ? (scanProgress.scanned / scanProgress.total) * 100
      : 0;

  return (
    <div className="shipment-editor">
      {/* Sticky Header */}
      <div className="sticky top-0 z-30 bg-gradient-to-l from-white to-[#DFF9FF] shadow-sm border-b border-gray-200 backdrop-blur-sm">
        <div className="px-4 md:px-6 py-4">
          {/* Desktop Header */}
          <div className="hidden sm:flex justify-between items-center">
            <div className="flex items-center">
              <h1 className="text-xl md:text-2xl font-bold text-gray-800">
                Scan Shipment {shipment.shipmentNumber}
              </h1>
            </div>
            <div className="flex items-center space-x-3">
              <button
                onClick={() => setIsMarkCompleteModalOpen(true)}
                disabled={isMarkingComplete}
                className="py-2 px-8 rounded-xl shadow transition-colors bg-green-600 text-white hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                {isMarkingComplete ? "Marking Complete..." : "Mark Complete"}
              </button>
            </div>
          </div>

          {/* Mobile Header */}
          <div className="sm:hidden space-y-4">
            <div className="text-center">
              <h1 className="text-lg font-bold text-gray-800">
                Scan Shipment {shipment.shipmentNumber}
              </h1>
            </div>
            <button
              onClick={() => setIsMarkCompleteModalOpen(true)}
              disabled={isMarkingComplete}
              className="w-full py-3 px-4 rounded-lg shadow transition-colors bg-green-600 text-white hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium touch-manipulation"
            >
              {isMarkingComplete ? "Marking Complete..." : "Mark Complete"}
            </button>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="m-4 md:m-6">
        {/* Desktop Layout */}
        <div className="hidden lg:grid lg:grid-cols-4 gap-6 flex-grow min-h-0">
          {/* Column 1: Barcode Scanner */}
          <div className="lg:col-span-2 flex flex-col h-[calc(100vh-185px)] bg-white rounded-lg shadow border p-4">
            <BarcodeScanner
              onBarcodeDetected={handleBarcodeDetected}
              scannerId="warehouse-shipment-scanner"
              title="Scan The Barcode On Pallet"
              manualPlaceholder="Enter Pallet Barcode"
              manualButtonText="Scan Pallet"
              className="flex-1"
            />
          </div>

          {/* Column 2: Shipment Details */}
          <div className="lg:col-span-2 bg-blue-50 p-4 rounded-lg shadow border border-blue-300 flex flex-col h-[calc(100vh-185px)]">
            <div className="flex-shrink-0">
              <div className="mb-4">
                <h2 className="text-base font-semibold text-gray-700 mb-2">
                  Scan Progress
                </h2>
              </div>

              {/* Search Pallet */}
              <div className="relative mb-4">
                <input
                  type="text"
                  placeholder={`Search by ${
                    searchFilter === "palletNumber"
                      ? "Pallet Number"
                      : searchFilter === "barcode"
                      ? "Barcode"
                      : "Order ID"
                  }`}
                  className="w-full p-3 pl-12 pr-12 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 text-black bg-white"
                  value={searchPallet}
                  onChange={(e) => setSearchPallet(e.target.value)}
                />
                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                  <MdSearch className="text-gray-400 h-5 w-5" />
                </div>
                <div className="absolute inset-y-0 right-0 pr-4 flex items-center">
                  <div className="relative" ref={filterDropdownRef}>
                    <button
                      className="flex items-center text-gray-400 hover:text-gray-600"
                      onClick={(e) => {
                        e.stopPropagation();
                        setIsFilterOpen(!isFilterOpen);
                      }}
                    >
                      <MdFilterList className="h-5 w-5 mr-1" />
                      <span className="text-sm">Filters</span>
                    </button>

                    {isFilterOpen && (
                      <div className="absolute right-0 top-full mt-2 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-10">
                        <div className="py-1">
                          <button
                            className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-100 ${
                              searchFilter === "palletNumber"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("palletNumber");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Pallet Number
                          </button>
                          <button
                            className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-100 ${
                              searchFilter === "barcode"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("barcode");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Barcode
                          </button>
                          <button
                            className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-100 ${
                              searchFilter === "orderId"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("orderId");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Order ID
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <h2 className="text-base font-semibold mb-3 text-gray-700">
                Pallets
              </h2>
            </div>
            <div className="space-y-3 overflow-y-auto pr-1 flex-grow no-scrollbar">
              {shipment?.shipmentPallets &&
              shipment.shipmentPallets.length > 0 ? (
                getSortedPallets(shipment.shipmentPallets).map(
                  (shipmentPallet: any) =>
                    renderPalletCard(shipmentPallet, false)
                )
              ) : (
                <p className="text-center text-gray-500 py-4">
                  No pallets in this shipment.
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Mobile Layout */}
        <div className="lg:hidden space-y-6">
          {/* Mobile: Barcode Scanner Section */}
          <BarcodeScanner
            onBarcodeDetected={handleBarcodeDetected}
            scannerId="warehouse-shipment-scanner-mobile"
            title="Scan The Barcode On Pallet"
            manualPlaceholder="Enter Pallet Barcode"
            manualButtonText="Scan Pallet"
          />

          {/* Mobile: Search and Product List Section */}
          <div className="bg-blue-50 p-4 rounded-lg shadow border border-blue-300">
            <div className="mb-4">
              <div className="flex items-center justify-between mb-3">
                <h2 className="text-lg font-semibold text-gray-700">Pallets</h2>
                <span className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">
                  {progressPercentage.toFixed(0)}% Complete
                </span>
              </div>

              {/* Search Product */}
              <div className="relative mb-4">
                <input
                  type="text"
                  placeholder={`Search by ${
                    searchFilter === "palletNumber"
                      ? "Pallet Number"
                      : searchFilter === "barcode"
                      ? "Barcode"
                      : "Order ID"
                  }`}
                  className="w-full p-3 pl-12 pr-12 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 text-black bg-white touch-manipulation"
                  value={searchPallet}
                  onChange={(e) => setSearchPallet(e.target.value)}
                />
                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                  <MdSearch className="text-gray-400 h-5 w-5" />
                </div>
                <div className="absolute inset-y-0 right-0 pr-4 flex items-center">
                  <div className="relative" ref={filterDropdownRef}>
                    <button
                      className="flex items-center text-gray-400 hover:text-gray-600 p-2 touch-manipulation"
                      onClick={(e) => {
                        e.stopPropagation();
                        setIsFilterOpen(!isFilterOpen);
                      }}
                    >
                      <MdFilterList className="h-5 w-5" />
                    </button>

                    {isFilterOpen && (
                      <div className="absolute right-0 top-full mt-2 w-48 bg-white border border-gray-200 rounded-md shadow-lg z-10">
                        <div className="py-1">
                          <button
                            className={`w-full text-left px-4 py-3 text-sm hover:bg-gray-100 touch-manipulation ${
                              searchFilter === "palletNumber"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("palletNumber");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Pallet Number
                          </button>
                          <button
                            className={`w-full text-left px-4 py-3 text-sm hover:bg-gray-100 touch-manipulation ${
                              searchFilter === "barcode"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("barcode");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Barcode
                          </button>
                          <button
                            className={`w-full text-left px-4 py-3 text-sm hover:bg-gray-100 touch-manipulation ${
                              searchFilter === "orderId"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("orderId");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Order ID
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Mobile Pallet List */}
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {shipment?.shipmentPallets &&
              shipment.shipmentPallets.length > 0 ? (
                getSortedPallets(shipment.shipmentPallets).map(
                  (shipmentPallet: any) =>
                    renderPalletCard(shipmentPallet, true)
                )
              ) : (
                <p className="text-center text-gray-500 py-4">
                  No pallets in this shipment.
                </p>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Custom CSS to hide scrollbar */}
      <style jsx>{`
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none; /* IE and Edge */
          scrollbar-width: none; /* Firefox */
        }
      `}</style>

      {/* Pallet Damage Modal */}
      {selectedPalletForDamage && (
        <MarkDamageModal
          isOpen={isPalletDamageModalOpen}
          onClose={handlePalletDamageModalClose}
          onSubmit={handlePalletDamageSubmit}
          productName={`Pallet #${selectedPalletForDamage.palletNumber}`}
          barcodeNumber={selectedPalletForDamage.palletBarcode}
          isSubmitting={isSubmitting}
          isEditMode={selectedPalletForDamage.isEdit}
          initialDescription={selectedPalletForDamage.description}
          initialImages={selectedPalletForDamage.images}
        />
      )}

      {/* Mark Pallet Missing Confirmation Modal */}
      {palletToMarkMissing && (
        <ConfirmationModal
          isOpen={true}
          onClose={() => setPalletToMarkMissing(null)}
          onConfirm={handleConfirmMarkMissing}
          title="Mark Pallet as Missing"
          description={`Are you sure Pallet #${palletToMarkMissing.palletNumber} did not arrive? Items on this pallet will not be added to stock.`}
          iconColor="#DC2626"
          iconContainerColor="#FEE2E2"
          confirmText="Yes, Mark Missing"
          cancelText="Cancel"
          autoCloseOnConfirm={false}
        />
      )}

      {/* Mark Complete Confirmation Modal */}
      <ConfirmationModal
        isOpen={isMarkCompleteModalOpen}
        onClose={() => setIsMarkCompleteModalOpen(false)}
        onConfirm={() => handleMarkComplete()}
        title="Mark Shipment Complete"
        description={`Are you sure you want to mark this shipment as completed?`}
        iconColor="#10B981"
        iconContainerColor="#D1FAE5"
        confirmText="Mark Complete"
        cancelText="Cancel"
        autoCloseOnConfirm={false}
      />

      {/* Unscanned Pallets Warning Modal */}
      {unscannedBarcodesInfo && (
        <ConfirmationModal
          isOpen={true}
          onClose={() => setUnscannedBarcodesInfo(null)}
          onConfirm={handleForceComplete}
          title="Unscanned Pallets Found"
          description={`Warning: ${unscannedBarcodesInfo.unscannedCount} of ${unscannedBarcodesInfo.totalCount} pallets have not been scanned or marked missing.\n\nProceeding will mark all unscanned pallets as missing.\n\nDo you still want to complete this shipment?`}
          iconColor="#F59E0B"
          iconContainerColor="#FEF3C7"
          confirmText="Yes, Mark Complete"
          cancelText="Cancel"
          autoCloseOnConfirm={false}
        />
      )}

      {/* Simple CSS for QuaggaJS styling */}
      <style jsx global>{`
        #warehouse-qr-reader,
        #warehouse-qr-reader-mobile {
          width: 100% !important;
          height: 192px !important;
        }
        #warehouse-qr-reader canvas,
        #warehouse-qr-reader video,
        #warehouse-qr-reader-mobile canvas,
        #warehouse-qr-reader-mobile video {
          width: 100% !important;
          height: 100% !important;
          object-fit: cover;
          border-radius: 8px;
        }

        /* Mobile-specific optimizations */
        @media (max-width: 768px) {
          #warehouse-qr-reader,
          #warehouse-qr-reader-mobile {
            height: 160px !important;
          }
          #warehouse-qr-reader canvas,
          #warehouse-qr-reader video,
          #warehouse-qr-reader-mobile canvas,
          #warehouse-qr-reader-mobile video {
            object-fit: cover;
          }
        }
      `}</style>
    </div>
  );
}
