"use client";

import React, { useState, useEffect } from "react";
import { MdQrCodeScanner, MdPallet, MdDelete } from "react-icons/md";
import { FiPrinter } from "react-icons/fi";
import BarcodeScanner from "@/components/ui/BarcodeScanner";
import FileUpload from "@/components/ui/FileUpload";
import ConfirmationModal from "@/components/ui/ConfirmationModal";
import { palletService } from "@/services/api";
import { ShipmentPallet, CreatePalletData, PalletStatus } from "@/types/pallet";
import { barcodeToastManager } from "@/utils/barcodeToastManager";
import { printBarcodes } from "@/utils/barcodePrint";

interface PalletTabsManagerProps {
  shipmentId: number;
  onPalletChange?: (pallets: ShipmentPallet[]) => void;
  activePalletId?: number | null;
  onActivePalletChange?: (palletId: number | null) => void;
}

export default function PalletTabsManager({
  shipmentId,
  onPalletChange,
  activePalletId: externalActivePalletId,
  onActivePalletChange,
}: PalletTabsManagerProps) {
  const [pallets, setPallets] = useState<ShipmentPallet[]>([]);
  const [internalActivePalletId, setInternalActivePalletId] = useState<
    number | null
  >(null);
  const [loading, setLoading] = useState(false);
  const [palletNumber, setPalletNumber] = useState(1);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [palletToDelete, setPalletToDelete] = useState<ShipmentPallet | null>(
    null
  );

  // Use external activePalletId if provided, otherwise use internal state
  const activePalletId =
    externalActivePalletId !== undefined
      ? externalActivePalletId
      : internalActivePalletId;

  const setActivePalletId = (palletId: number | null) => {
    if (onActivePalletChange) {
      onActivePalletChange(palletId);
    } else {
      setInternalActivePalletId(palletId);
    }
  };

  useEffect(() => {
    initializePallets();
  }, [shipmentId]);

  const initializePallets = async () => {
    try {
      setLoading(true);
      const response = await palletService.getShipmentPallets(shipmentId);
      setPallets(response.data);

      // Always notify parent component of pallet changes
      if (onPalletChange) {
        onPalletChange(response.data);
      }

      // If no pallets exist, create the first one
      if (response.data.length === 0) {
        await createInitialPallet();
      } else {
        // Calculate next pallet number
        const maxPalletNumber =
          response.data.length > 0
            ? Math.max(
                ...response.data.map((p: ShipmentPallet) => p.palletNumber)
              )
            : 0;
        setPalletNumber(maxPalletNumber + 1);

        // Set first pallet as active if none is selected
        if (!activePalletId) {
          setActivePalletId(response.data[0].id);
        }
      }
    } catch (error: any) {
      console.error("Error initializing pallets:", error);
      barcodeToastManager.addErrorToast("Failed to load pallets");
    } finally {
      setLoading(false);
    }
  };

  const loadPallets = async () => {
    try {
      setLoading(true);
      const response = await palletService.getShipmentPallets(shipmentId);
      setPallets(response.data);

      // Always notify parent component of pallet changes
      if (onPalletChange) {
        onPalletChange(response.data);
      }

      // Calculate next pallet number
      const maxPalletNumber =
        response.data.length > 0
          ? Math.max(
              ...response.data.map((p: ShipmentPallet) => p.palletNumber)
            )
          : 0;
      setPalletNumber(maxPalletNumber + 1);

      // Set first pallet as active if none is selected
      if (response.data.length > 0 && !activePalletId) {
        setActivePalletId(response.data[0].id);
      }
    } catch (error) {
      console.error("Error loading pallets:", error);
      barcodeToastManager.addErrorToast("Failed to load pallets");
    } finally {
      setLoading(false);
    }
  };

  const createInitialPallet = async () => {
    try {
      // Create the first pallet (barcode will be generated automatically)
      const palletResponse = await palletService.createPallet({
        status: PalletStatus.AVAILABLE,
      });
      const createdPallet = palletResponse.data;

      // Create the shipment pallet relationship with pallet number 1
      const shipmentPalletData = {
        palletId: Number(createdPallet.id), // Ensure it's a number
        palletNumber: 1,
        items: [],
      };

      console.log("Creating initial pallet with data:", shipmentPalletData);
      await palletService.createShipmentPallet(shipmentId, shipmentPalletData);

      // Reload pallets to get the updated list
      const response = await palletService.getShipmentPallets(shipmentId);
      setPallets(response.data);
      setActivePalletId(response.data[0].id);
      setPalletNumber(2); // Next pallet will be number 2

      if (onPalletChange) {
        onPalletChange(response.data);
      }

      // No toast message for initial pallet creation
    } catch (error: any) {
      console.error("Error creating initial pallet:", error);

      // If there's a conflict, try to load existing pallets instead
      if (error.response?.data?.message?.includes("already exists")) {
        console.log("Pallet already exists, loading existing pallets...");
        await loadPallets();
      } else {
        barcodeToastManager.addErrorToast("Failed to create initial pallet");
      }
    }
  };

  const handleCreatePallet = async () => {
    try {
      setLoading(true);

      // Create the pallet first (barcode will be generated automatically)
      const palletResponse = await palletService.createPallet({
        status: PalletStatus.AVAILABLE,
      });
      const createdPallet = palletResponse.data;

      // Create the shipment pallet relationship with sequential number
      const shipmentPalletData = {
        palletId: Number(createdPallet.id), // Ensure it's a number
        palletNumber: palletNumber,
        items: [],
      };

      await palletService.createShipmentPallet(shipmentId, shipmentPalletData);

      await loadPallets();
      barcodeToastManager.addSuccessToast(
        `Pallet ${palletNumber} created successfully`
      );
    } catch (error: any) {
      console.error("Error creating pallet:", error);

      // Handle specific error cases
      if (error.response?.data?.message?.includes("already exists")) {
        barcodeToastManager.addErrorToast(
          "Pallet number already exists. Please try again."
        );
        // Reload pallets to get the updated list and recalculate next number
        await loadPallets();
      } else {
        barcodeToastManager.addErrorToast("Failed to create pallet");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleScanBarcode = async (barcodeCode: string) => {
    if (!activePalletId) return;

    const activePallet = pallets.find((p) => p.id === activePalletId);
    if (!activePallet) return;

    try {
      await palletService.addBarcodeToShipmentPallet(
        shipmentId,
        activePallet.palletNumber,
        barcodeCode
      );
      await loadPallets();
      barcodeToastManager.addSuccessToast(
        `Item added to pallet ${activePallet.palletNumber}`
      );
    } catch (error: any) {
      console.error("Error adding item to pallet:", error);

      // Extract error message from backend response
      const errorMessage =
        error.response?.data?.message ||
        error.message ||
        "Failed to add item to pallet";
      barcodeToastManager.addErrorToast(errorMessage);
    }
  };

  const handleFileUpload = async (files: File[]) => {
    try {
      // Handle file upload for pallet documents
      // This would integrate with your existing file upload logic
      barcodeToastManager.addSuccessToast(
        `${files.length} files uploaded successfully`
      );
    } catch (error) {
      console.error("Error uploading files:", error);
      barcodeToastManager.addErrorToast("Failed to upload files");
    }
  };

  const handleDeletePallet = async (pallet: ShipmentPallet) => {
    setPalletToDelete(pallet);
    setShowDeleteConfirm(true);
  };

  const handleConfirmDelete = async () => {
    if (!palletToDelete) return;

    try {
      setLoading(true);

      // Store the current pallet number before deletion for reference
      const deletedPalletNumber = palletToDelete.palletNumber;
      const wasActivePallet = activePalletId === palletToDelete.id;

      await palletService.deleteShipmentPallet(palletToDelete.id);

      // Reload pallets to get the updated list with renumbered pallets
      await loadPallets();

      // If the deleted pallet was active, select the previous pallet
      if (wasActivePallet) {
        // Find the pallet that should be selected (previous pallet)
        // Since pallets are renumbered, we need to find the pallet that was before the deleted one
        const remainingPallets = pallets.filter(
          (p) => p.id !== palletToDelete.id
        );

        if (remainingPallets.length > 0) {
          // Find the pallet that should be selected
          // If we deleted pallet 2, we want to select the pallet that was pallet 1
          // If we deleted pallet 1, we want to select the pallet that was pallet 2 (now renumbered to 1)
          let palletToSelect = null;

          if (deletedPalletNumber === 1) {
            // If we deleted pallet 1, select the first remaining pallet (which was pallet 2)
            palletToSelect = remainingPallets[0];
          } else {
            // If we deleted a higher numbered pallet, select the previous pallet
            // Find the pallet with the highest number less than the deleted pallet
            const previousPallets = remainingPallets.filter(
              (p) => p.palletNumber < deletedPalletNumber
            );
            if (previousPallets.length > 0) {
              palletToSelect = previousPallets[previousPallets.length - 1]; // Get the last (highest numbered) previous pallet
            } else {
              // No previous pallet, select the first remaining pallet
              palletToSelect = remainingPallets[0];
            }
          }

          if (palletToSelect) {
            setActivePalletId(palletToSelect.id);
          }
        } else {
          // No pallets remaining
          setActivePalletId(null);
        }
      }

      barcodeToastManager.addSuccessToast(
        `Pallet ${deletedPalletNumber} deleted successfully. Remaining pallets have been renumbered.`
      );
    } catch (error: any) {
      console.error("Error deleting pallet:", error);
      barcodeToastManager.addErrorToast(
        error.response?.data?.message || "Failed to delete pallet"
      );
    } finally {
      setLoading(false);
      setShowDeleteConfirm(false);
      setPalletToDelete(null);
    }
  };

  const handleCancelDelete = () => {
    setShowDeleteConfirm(false);
    setPalletToDelete(null);
  };

  const handlePrintPalletBarcode = (pallet: ShipmentPallet) => {
    if (!pallet.pallet.barcode) {
      barcodeToastManager.addErrorToast("No barcode available for this pallet");
      return;
    }

    const palletBarcode = {
      id: pallet.pallet.barcode.id,
      code: pallet.pallet.barcode.code,
      productName: `Pallet #${pallet.palletNumber}`,
      productImage: undefined,
    };

    printBarcodes([palletBarcode], {
      title: `Pallet #${pallet.palletNumber}`,
      orderNumber: `Shipment #${shipmentId}`,
      quantity: 1,
    });
  };

  const activePallet = pallets.find((p) => p.id === activePalletId);

  return (
    <div className="w-full">
      {/* Compact Pallet Management */}
      {/* Header with Pallet Tabs and Create Button */}
      <div className="p-4">
        <div className="flex justify-between items-center mb-4">
          <div className="flex items-center space-x-4">
            <h3 className="font-bold text-gray-700">Pallets</h3>
          </div>
          <button
            onClick={handleCreatePallet}
            disabled={loading}
            className="flex items-center gap-1 px-3 py-1 bg-[#0C2C4A] text-white rounded-lg text-sm hover:bg-[#0C2C4A]/80 transition-colors disabled:opacity-50"
          >
            <MdPallet className="w-3 h-3" />
            {loading ? "Creating..." : "Create Pallet"}
          </button>
        </div>

        {/* Pallet Tabs */}
        <div className="flex space-x-1 overflow-x-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 py-2 px-1">
          {pallets.map((pallet) => (
            <div
              key={pallet.id}
              className={`flex items-center gap-1 px-3 py-1 text-xs font-medium border-b-2 transition-colors whitespace-nowrap rounded-t-lg ${
                activePalletId === pallet.id
                  ? "border-blue-500 text-blue-600 bg-blue-50"
                  : "border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50"
              }`}
            >
              <button
                onClick={() => setActivePalletId(pallet.id)}
                className="flex items-center gap-1"
              >
                Pallet {pallet.palletNumber}
              </button>
              {pallets.length > 1 && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeletePallet(pallet);
                  }}
                  className="ml-1 p-1 hover:bg-red-100 rounded text-red-500 hover:text-red-700 transition-colors"
                  title="Delete pallet"
                >
                  <MdDelete size={12} />
                </button>
              )}
            </div>
          ))}
        </div>

        {/* Active Pallet Barcode Display */}
        {activePallet && (
          <div className="mt-3 bg-gray-100 p-2 rounded">
            <div className="flex items-center justify-between text-sm">
              <div className="flex items-center gap-2">
                <MdQrCodeScanner className="w-3 h-3" />
                <span className="text-gray-600">Pallet Barcode:</span>
                <span className="font-bold text-gray-800">
                  {activePallet.pallet.barcode?.code ||
                    `P${activePallet.palletNumber
                      .toString()
                      .padStart(2, "0")}-${activePallet.id}`}
                </span>
              </div>
              {activePallet.pallet.barcode && (
                <button
                  onClick={() => handlePrintPalletBarcode(activePallet)}
                  className="flex items-center gap-1 px-2 py-1 bg-white text-gray-700 rounded border border-gray-300 hover:bg-gray-50 transition-colors text-xs"
                  title="Print pallet barcode"
                >
                  <FiPrinter size={12} />
                  Print
                </button>
              )}
            </div>
          </div>
        )}

        {/* Barcode Scanner for adding items to pallet */}
        {activePallet && (
          <div className="mt-6">
            <BarcodeScanner
              onBarcodeDetected={handleScanBarcode}
              scannerId={`pallet-scanner-${activePallet.id}`}
              title={`Scan items for Pallet ${activePallet.palletNumber}`}
              manualPlaceholder="Enter barcode"
              manualButtonText="Add to Pallet"
            />
          </div>
        )}
      </div>

      {/* Delete Confirmation Modal */}
      <ConfirmationModal
        isOpen={showDeleteConfirm}
        onClose={handleCancelDelete}
        onConfirm={handleConfirmDelete}
        title="Delete Pallet"
        description={
          palletToDelete
            ? `Are you sure you want to delete Pallet ${
                palletToDelete.palletNumber
              }? This pallet contains ${
                palletToDelete.shipmentPalletItems?.length || 0
              } product(s). This action cannot be undone and will remove all items from this pallet.`
            : ""
        }
        confirmText="Delete"
        cancelText="Cancel"
        iconColor="#DC2626"
        iconContainerColor="#FEE2E2"
      />
    </div>
  );
}
