"use client";

import React, { useState, useEffect, useRef, useCallback } from "react";
import {
  MdFolderOpen,
  MdAdd,
  MdRemove,
  MdSearch,
  MdFilterList,
} from "react-icons/md";
import FileUpload from "@/components/ui/FileUpload";
import { useFileUpload } from "@/hooks/useFileUpload";
import { useProductManager } from "@/hooks/useProductManager";

import {
  getGoogleDriveConfig,
  validateGoogleDriveConfig,
} from "@/config/googleDrive";
import {
  Product,
  Supplier,
  Warehouse,
} from "../../../../../../types/purchase-order";
import {
  ShipmentProductData,
  CreateShipmentData,
  UpdateShipmentData,
  Shipment,
} from "../../../../../../types/shipment";
import {
  purchaseOrderService,
  manageOrdersService,
  shipmentService,
  palletService,
} from "../../../../../../services/api";
import { useRouter } from "next/navigation";
import { validateShipmentData } from "../../../../../../utils/shipmentValidation";
import { barcodeToastManager } from "../../../../../../utils/barcodeToastManager";
import PalletTabsManager from "../../../../../../components/pallet/PalletTabsManager";
import { ShipmentPallet } from "../../../../../../types/pallet";
import ConfirmationModal from "../../../../../../components/ui/ConfirmationModal";

interface ScannedProduct {
  id: number;
  name: string;
  quantity: number;
}

interface ShipmentEditorProps {
  mode: "create" | "edit";
  shipmentId?: number;
  title: string;
  actionButtonText: string;
  onSuccess?: (shipmentId: number) => void;
}

export default function ShipmentEditor({
  mode,
  shipmentId,
  title,
  actionButtonText,
  onSuccess,
}: ShipmentEditorProps) {
  const router = useRouter();
  const filterDropdownRef = useRef<HTMLDivElement>(null);

  const [products, setProducts] = useState<Product[]>([]);
  const [shipment, setShipment] = useState<Shipment | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [autoCreatedShipmentId, setAutoCreatedShipmentId] = useState<
    number | null
  >(null);
  const hasAutoCreated = useRef(false);
  const [searchProduct, setSearchProduct] = useState("");
  const [searchFilter, setSearchFilter] = useState<
    "name" | "barcode" | "orderId"
  >("name");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [pallets, setPallets] = useState<ShipmentPallet[]>([]);
  const [activePalletId, setActivePalletId] = useState<number | null>(null);

  // Confirmation modal state
  const [showRemoveConfirm, setShowRemoveConfirm] = useState(false);
  const [itemToRemove, setItemToRemove] = useState<{
    barcode: string;
    productName: string;
  } | null>(null);

  // Custom hooks
  const productManager = useProductManager();

  // File upload configuration and hook
  const googleDriveConfig = getGoogleDriveConfig();
  const isConfigValid = validateGoogleDriveConfig(googleDriveConfig);

  // Mock user ID - replace with actual user ID from your auth system
  const userId = 1; // TODO: Get from auth context

  const {
    uploadedFiles,
    uploadProgress,
    isUploading,
    handleFileSelect,
    removeFile,
    cancelUpload,
    setUploadedFilesFromDocuments,
  } = useFileUpload({
    config: googleDriveConfig,
    userId,
    purchaseOrderId: autoCreatedShipmentId || shipmentId, // Use auto-created shipment ID
    onSaveToDatabase: async (documentData: any) => {
      const currentShipmentId = autoCreatedShipmentId || shipmentId;
      if (currentShipmentId) {
        try {
          await shipmentService.addDocumentToShipment(currentShipmentId, {
            filename: documentData.filename,
            drive_file_id: documentData.drive_file_id,
          });
          barcodeToastManager.addSuccessToast(
            `Document ${documentData.filename} added to shipment`
          );
        } catch (error: any) {
          barcodeToastManager.addErrorToast(
            error.response?.data?.message ||
              `Failed to add document ${documentData.filename} to shipment`
          );
          throw error;
        }
      }
    },
    onDeleteFromDatabase: async (driveFileId: string) => {
      const currentShipmentId = autoCreatedShipmentId || shipmentId;
      if (currentShipmentId) {
        try {
          await shipmentService.removeDocumentFromShipment(
            currentShipmentId,
            driveFileId
          );
          // No toast needed - user can see the document was removed from UI
        } catch (error: any) {
          barcodeToastManager.addErrorToast(
            error.response?.data?.message ||
              `Failed to remove document from shipment`
          );
          throw error;
        }
      }
    },
  });

  const [existingDocumentIds, setExistingDocumentIds] = useState<Set<string>>(
    new Set()
  );

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);

        if (mode === "create" && !hasAutoCreated.current) {
          // Auto-create empty shipment on page load (only once)
          hasAutoCreated.current = true;

          const emptyShipmentData = {
            status: "draft",
            description: "",
            actor_id: userId,
          };

          try {
            const response = await shipmentService.createShipment(
              emptyShipmentData
            );
            const createdShipment = response.data;
            setAutoCreatedShipmentId(createdShipment.id);
            setShipment(createdShipment);

            // No toast message needed - user will see the visual indicator
          } catch (error) {
            console.error("Failed to create empty shipment:", error);
            barcodeToastManager.addErrorToast(
              "Failed to create shipment. Please try again."
            );
          }

          // Fetch products for create mode
          const productsRes = await manageOrdersService.getAllProducts();
          setProducts(productsRes.data);
        } else if (mode === "edit" && shipmentId) {
          // Fetch existing shipment data and products for edit mode
          const [shipmentRes, productsRes] = await Promise.all([
            shipmentService.getShipment(shipmentId),
            manageOrdersService.getAllProducts(),
          ]);

          const shipmentData = shipmentRes.data;
          setShipment(shipmentData);
          setProducts(productsRes.data);

          // Pre-populate selected products from existing pallet items
          const existingProducts: ShipmentProductData[] = [];
          if (shipmentData.shipmentPallets) {
              for (const sp of shipmentData.shipmentPallets) {
                  if (sp.shipmentPalletItems) {
                      for (const item of sp.shipmentPalletItems) {
                          existingProducts.push({
                              productId: item.barcode?.purchaseOrderItem?.product?.id || item.barcode?.product?.id || 0,
                              quantity: 1,
                              barcode: item.barcode?.code,
                          });
                      }
                  }
              }
          }

          productManager.setProducts(existingProducts);

          // Set existing documents
          if (shipmentData.documents && shipmentData.documents.length > 0) {
            setUploadedFilesFromDocuments(shipmentData.documents);
            const documentIds = new Set<string>();
            shipmentData.documents.forEach((doc: any) => {
              if (doc.driveFileId) {
                documentIds.add(doc.driveFileId);
              }
            });
            setExistingDocumentIds(documentIds);
          }
        }

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

    fetchData();
  }, [mode, shipmentId]);

  // Load pallets when autoCreatedShipmentId or shipmentId changes
  useEffect(() => {
    if (autoCreatedShipmentId || (mode === "edit" && shipmentId)) {
      loadPallets();
    }
  }, [autoCreatedShipmentId, mode, 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]);

  const selectedProductIds = productManager.selectedProducts.map(
    (item) => item.productId
  );

  const handleAddProductByBarcode = useCallback(
    async (barcode: string) => {
      // Check for duplicates first
      if (productManager.hasBarcode(barcode)) {
        barcodeToastManager.addErrorToast(
          `Barcode ${barcode} has already been added to this shipment`
        );
        return;
      }

      // Check if we have an active pallet
      if (pallets.length === 0) {
        barcodeToastManager.addErrorToast(
          "No pallets available. Please create a pallet first."
        );
        return;
      }

      // Find the active pallet (first pallet if none is explicitly selected)
      const activePallet =
        pallets.find((p) => p.id === activePalletId) || pallets[0];
      if (!activePallet) {
        barcodeToastManager.addErrorToast(
          "No active pallet found. Please select a pallet first."
        );
        return;
      }

      // Add barcode directly to the active pallet
      if (autoCreatedShipmentId) {
        try {
          await palletService.addBarcodeToShipmentPallet(
            autoCreatedShipmentId,
            activePallet.palletNumber,
            barcode
          );
          // Reload pallets to get updated data
          loadPallets();
          barcodeToastManager.addSuccessToast(
            `Barcode ${barcode} added to pallet ${activePallet.palletNumber}`
          );
        } catch (error: any) {
          barcodeToastManager.addErrorToast(
            error.response?.data?.message ||
              `Failed to add barcode ${barcode} to pallet ${activePallet.palletNumber}`
          );
        }
      }
    },
    [autoCreatedShipmentId, pallets, activePalletId]
  );

  const handleRemoveProduct = useCallback(
    async (productId: number, barcode?: string) => {
      // Remove from local state first
      productManager.removeProduct(productId, barcode);

      if (autoCreatedShipmentId && barcode) {
        // Find the pallet that contains this barcode
        const palletWithBarcode = pallets.find((pallet) =>
          pallet.shipmentPalletItems?.some(
            (item) => item.barcode?.code === barcode
          )
        );

        if (palletWithBarcode) {
          // Update database by removing barcode from the pallet
          try {
            await palletService.removeBarcodeFromShipmentPallet(
              autoCreatedShipmentId,
              palletWithBarcode.palletNumber,
              barcode
            );
            // Reload pallets to get updated data
            loadPallets();
            // No toast needed - user can see the product was removed from UI
          } catch (error: any) {
            // Re-add to local state if database update failed
            // Note: We'd need to get the product data to re-add it
            barcodeToastManager.addErrorToast(
              error.response?.data?.message ||
                `Failed to remove barcode ${barcode} from pallet ${palletWithBarcode.palletNumber}`
            );
          }
        } else {
          barcodeToastManager.addErrorToast(
            `Barcode ${barcode} not found in any pallet`
          );
        }
      }
    },
    [productManager, autoCreatedShipmentId, pallets]
  );

  const handleRemovePalletItem = useCallback(
    async (barcode: string) => {
      if (!barcode) return;

      // Find the pallet that contains this barcode
      const palletWithBarcode = pallets.find((pallet) =>
        pallet.shipmentPalletItems?.some(
          (item) => item.barcode?.code === barcode
        )
      );

      if (palletWithBarcode) {
        try {
          await palletService.removeBarcodeFromShipmentPallet(
            shipmentId || autoCreatedShipmentId!,
            palletWithBarcode.palletNumber,
            barcode
          );
          // Reload pallets to get updated data
          await loadPallets();
          barcodeToastManager.addSuccessToast(
            `Item removed from pallet ${palletWithBarcode.palletNumber}`
          );
        } catch (error: any) {
          barcodeToastManager.addErrorToast(
            error.response?.data?.message ||
              `Failed to remove barcode ${barcode} from pallet ${palletWithBarcode.palletNumber}`
          );
        }
      } else {
        barcodeToastManager.addErrorToast("Item not found in any pallet");
      }
    },
    [shipmentId, autoCreatedShipmentId, pallets]
  );

  const handleConfirmRemoveItem = useCallback(
    async (barcode: string, productName: string) => {
      setItemToRemove({ barcode, productName });
      setShowRemoveConfirm(true);
    },
    []
  );

  const handleCloseRemoveModal = useCallback(() => {
    setShowRemoveConfirm(false);
    setItemToRemove(null);
  }, []);

  const handleConfirmRemove = useCallback(async () => {
    if (itemToRemove) {
      await handleRemovePalletItem(itemToRemove.barcode);
      handleCloseRemoveModal();
    }
  }, [itemToRemove, handleRemovePalletItem, handleCloseRemoveModal]);

  const handleSubmit = async () => {
    try {
      setIsSubmitting(true);

      // Skip validation for auto-creation
      // const validation = validateShipmentData(
      //   null, // No shipment date required
      //   productManager.selectedProducts
      // );
      // if (!validation.isValid) {
      //   validation.errors.forEach((error) =>
      //     barcodeToastManager.addErrorToast(error)
      //   );
      //   return;
      // }

      if (mode === "create") {
        if (autoCreatedShipmentId) {
          // Just redirect to shipment details page
          router.push(`/manufacturer/shipments/${autoCreatedShipmentId}`);
        } else {
          // Fallback: Create new shipment if auto-creation failed
          const shipmentData = {
            status: "draft",
            description: "",
            actor_id: userId,
            documents: uploadedFiles.map((file) => ({
              filename: file.name,
              drive_file_id: file.driveFileId,
            })),
          };

          const response = await shipmentService.createShipment(shipmentData);
          const createdShipment = response.data;

          router.push(`/manufacturer/shipments/${createdShipment.id}`);
        }
      } else if (mode === "edit" && shipmentId) {
        // In edit mode, everything is saved automatically (barcodes, documents, pallets)
        // So we just need to redirect to the shipment detail page
        if (onSuccess) {
          onSuccess(shipmentId);
        } else {
          // Redirect to shipment detail page
          router.push(`/manufacturer/shipments/${shipmentId}`);
        }
      }
    } catch (error: any) {
      console.error(
        `Error ${mode === "create" ? "creating" : "updating"} shipment:`,
        error
      );
      if (error.response?.data?.message) {
        barcodeToastManager.addErrorToast(error.response.data.message);
      } else {
        barcodeToastManager.addErrorToast(
          `Failed to ${
            mode === "create" ? "create" : "update"
          } shipment. Please try again.`
        );
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const loadPallets = async () => {
    const currentShipmentId = autoCreatedShipmentId || shipmentId;
    if (currentShipmentId) {
      try {
        const response = await palletService.getShipmentPallets(
          currentShipmentId
        );
        setPallets(response.data);
      } catch (error) {
        console.error("Error loading pallets:", error);
      }
    }
  };

  const handlePalletChange = (updatedPallets: ShipmentPallet[]) => {
    setPallets(updatedPallets);
    // Set the first pallet as active if none is selected
    if (updatedPallets.length > 0 && !activePalletId) {
      setActivePalletId(updatedPallets[0].id);
    }
  };

  // Note: We now use pallet data directly instead of productManager.selectedProducts
  // The scan summary and shipment details are now based on pallet items

  // Loading state
  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>
    );
  }

  // Error state
  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.push("/manufacturer")}
          className="mt-4 bg-white text-red-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back to Manufacturer
        </button>
      </div>
    );
  }

  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">
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center space-y-4 sm:space-y-0">
            <div>
              <h1 className="text-xl md:text-2xl font-bold text-gray-800">
                {title}
              </h1>
            </div>
            <button
              onClick={handleSubmit}
              disabled={isSubmitting}
              className={`bg-[#3997E0] text-white py-2 px-4 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center sm:justify-start w-full sm:w-auto ${
                isSubmitting
                  ? "opacity-50 cursor-not-allowed"
                  : "hover:bg-blue-700"
              }`}
            >
              {isSubmitting ? "Proceeding..." : "Proceed"}
            </button>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="m-4 md:m-6">
        <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 flex-grow min-h-0">
          {/* Column 1: Barcode Scanner with Pallet Management */}
          <div className="xl:col-span-1 flex flex-col lg:h-[calc(100vh-190px)] bg-white rounded-lg shadow border">
            {/* Pallet Management Section */}
            {(autoCreatedShipmentId || (mode === "edit" && shipmentId)) && (
              <PalletTabsManager
                shipmentId={autoCreatedShipmentId || shipmentId!}
                onPalletChange={handlePalletChange}
                activePalletId={activePalletId}
                onActivePalletChange={setActivePalletId}
              />
            )}
          </div>

          {/* Column 2: Shipment Details */}
          <div className="xl:col-span-1 bg-blue-50 p-4 rounded-lg shadow border border-blue-300 flex flex-col h-[calc(100vh-190px)]">
            <div className="flex-shrink-0">
              <div className="mb-4">
                <div className="flex items-center justify-between mb-2">
                  <h2 className="text-base font-semibold text-gray-700">
                    Shipment Details
                  </h2>
                  <span className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">
                    Status: Draft
                  </span>
                </div>
              </div>

              {/* Search Product */}
              <div className="relative mb-4">
                <input
                  type="text"
                  placeholder={`Search by ${
                    searchFilter === "name"
                      ? "Product Name"
                      : 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={searchProduct}
                  onChange={(e) => {
                    setSearchProduct(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 === "name"
                                ? "bg-blue-50 text-blue-600"
                                : "text-gray-700"
                            }`}
                            onClick={(e) => {
                              e.stopPropagation();
                              setSearchFilter("name");
                              setIsFilterOpen(false);
                            }}
                          >
                            Search by Product Name
                          </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">
                Products
              </h2>
            </div>
            <div className="space-y-2 overflow-y-auto pr-1 flex-grow no-scrollbar">
              {pallets.length === 0 ? (
                <p className="text-center text-gray-500 py-4">
                  No pallets created yet. Create a pallet first to start
                  scanning items.
                </p>
              ) : !activePalletId ? (
                <p className="text-center text-gray-500 py-4">
                  Please select a pallet to view its items.
                </p>
              ) : (
                (() => {
                  // Get the active pallet
                  const activePallet = pallets.find(
                    (p) => p.id === activePalletId
                  );
                  if (!activePallet) {
                    return (
                      <p className="text-center text-gray-500 py-4">
                        Active pallet not found.
                      </p>
                    );
                  }

                  const palletItems = activePallet.shipmentPalletItems || [];

                  // Filter items based on search
                  const filteredItems = palletItems.filter((item) => {
                    if (!searchProduct) return true;
                    const searchLower = searchProduct.toLowerCase();

                    switch (searchFilter) {
                      case "name":
                        return item.barcode?.product?.name
                          ?.toLowerCase()
                          .includes(searchLower);
                      case "barcode":
                        return item.barcode?.code
                          ?.toLowerCase()
                          .includes(searchLower);
                      case "orderId":
                        return item.barcode?.purchaseOrderItem?.purchaseOrder?.orderNumber
                          ?.toLowerCase()
                          .includes(searchLower);
                      default:
                        return true;
                    }
                  });

                  return filteredItems.length === 0 ? (
                    <p className="text-center text-gray-500 py-4">
                      {searchProduct
                        ? "No items found matching your search criteria in this pallet."
                        : "No items in this pallet yet."}
                    </p>
                  ) : (
                    filteredItems.map((item) => (
                      <div
                        key={item.id}
                        className="flex items-center justify-between p-3 bg-white rounded-lg shadow"
                      >
                        <div className="flex items-center flex-grow">
                          <div className="flex-grow">
                            <h3 className="font-semibold text-sm text-gray-900 mb-1">
                              {item.barcode?.product?.name || "Unknown Product"}
                            </h3>
                            <div className="flex flex-col space-y-1">
                              <div className="flex items-center text-xs text-gray-600">
                                <span className="font-medium">Barcode</span>
                                <span className="ml-1">
                                  {item.barcode?.code || "N/A"}
                                </span>
                              </div>
                              <div className="flex items-center text-xs text-blue-600">
                                <span className="font-medium">Order ID</span>
                                <span className="ml-1">
                                  {item.barcode?.purchaseOrderItem
                                    ?.purchaseOrder?.orderNumber || "N/A"}
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          <button
                            onClick={() =>
                              handleConfirmRemoveItem(
                                item.barcode?.code,
                                item.barcode?.product?.name || "Unknown Product"
                              )
                            }
                            className="px-3 py-1 text-xs text-red-600 hover:text-red-800 hover:bg-red-50 rounded transition-colors"
                          >
                            Remove
                          </button>
                        </div>
                      </div>
                    ))
                  );
                })()
              )}
            </div>
          </div>

          {/* Column 3: Scan Summary and File Upload */}
          <div className="xl:col-span-1 flex flex-col h-[calc(100vh-190px)]">
            {/* Scan Summary Section - 50% height */}
            <div className="flex-1 flex flex-col min-h-0 mb-4 p-4 bg-white rounded-lg shadow">
              <div className="pb-2 flex-shrink-0">
                <h3 className="text-md font-semibold text-gray-800">
                  Scan Summary
                </h3>
              </div>

              <div className="flex-1 min-h-0 overflow-hidden">
                {pallets.length === 0 ? (
                  <div className="p-4 text-center text-gray-500 text-sm">
                    No pallets created yet
                  </div>
                ) : (
                  (() => {
                    // Get the active pallet
                    const activePallet = pallets.find(
                      (p) => p.id === activePalletId
                    );

                    if (!activePallet) {
                      return (
                        <div className="p-4 text-center text-gray-500 text-sm">
                          Please select a pallet to view its items.
                        </div>
                      );
                    }

                    const palletItems = activePallet.shipmentPalletItems || [];
                    const totalItems = palletItems.length;

                    if (totalItems === 0) {
                      return (
                        <div className="p-4 text-center text-gray-500 text-sm">
                          No items in this pallet yet. Use the barcode scanner
                          to add items.
                        </div>
                      );
                    }

                    // Aggregate products by name and count quantities
                    const productSummary = palletItems.reduce((acc, item) => {
                      const productName =
                        item.barcode?.product?.name || "Unknown Product";

                      if (acc[productName]) {
                        acc[productName] += 1;
                      } else {
                        acc[productName] = 1;
                      }

                      return acc;
                    }, {} as Record<string, number>);

                    const productEntries = Object.entries(productSummary);

                    return (
                      <div className="h-full rounded-lg border border-gray-200 bg-gradient-to-l from-white to-[#DFF9FF] flex flex-col">
                        <div className="overflow-y-auto flex-1 no-scrollbar">
                          <table className="w-full">
                            <thead className="sticky top-0 bg-gray-100 z-10">
                              <tr>
                                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-800 border-b border-gray-200">
                                  Products ({productEntries.length})
                                </th>
                                <th className="px-4 py-3 text-center text-sm font-semibold text-gray-800 w-20 border-b border-gray-200">
                                  Total
                                </th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                              {productEntries.map(
                                ([productName, quantity], index) => (
                                  <tr
                                    key={productName}
                                    className={`border-b-2 border-white ${
                                      index % 2 === 0
                                        ? "bg-blue-50"
                                        : "bg-white"
                                    }`}
                                  >
                                    <td className="px-4 py-3 text-sm font-medium text-gray-900">
                                      {productName}
                                    </td>
                                    <td className="px-4 py-3 text-sm font-medium text-gray-900 text-center">
                                      {quantity}
                                    </td>
                                  </tr>
                                )
                              )}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    );
                  })()
                )}
              </div>
            </div>

            {/* File Upload Section - 50% height */}
            <div className="flex-1 flex flex-col min-h-0 bg-gray-50 p-4 rounded-lg shadow">
              <div className="flex-shrink-0">
                <h2 className="text-base font-semibold mb-3 text-gray-700">
                  Upload Files (optional)
                </h2>
                {!isConfigValid && (
                  <div className="mb-3 p-2 bg-yellow-100 border border-yellow-400 rounded text-xs text-yellow-700">
                    Google Drive configuration is incomplete. Please check your
                    settings.
                  </div>
                )}
              </div>
              <div className="flex-1 min-h-0">
                <FileUpload
                  onFileSelect={handleFileSelect}
                  uploadedFiles={uploadedFiles}
                  uploadProgress={uploadProgress}
                  isUploading={isUploading}
                  onRemoveFile={removeFile}
                  onCancelUpload={cancelUpload}
                  accept="*/*"
                  multiple={true}
                  maxSize={100000000} // 100MB
                  className="h-full"
                />
              </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>
      </div>

      {/* Confirmation Modal for removing pallet items */}
      {showRemoveConfirm && itemToRemove && (
        <ConfirmationModal
          isOpen={showRemoveConfirm}
          onClose={handleCloseRemoveModal}
          onConfirm={handleConfirmRemove}
          title="Remove Item"
          description={`Are you sure you want to remove "${itemToRemove.productName}" (${itemToRemove.barcode}) from the pallet? This action cannot be undone.`}
          iconContainerColor="#FFE5E5"
          iconColor="#DC2626"
          confirmText="Remove"
          cancelText="Cancel"
        />
      )}
    </div>
  );
}
