"use client";

import React, { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
import {
  MdEdit,
  MdInfo,
  MdCancel,
  MdExpandMore,
  MdExpandLess,
} from "react-icons/md";
import { FiX, FiPrinter } from "react-icons/fi";
import { shipmentService } from "@/services/api";
import { Shipment, ShipmentStatus, ShipmentDocument } from "@/types/shipment";
import { getDocumentFileIcon } from "@/utils/fileIcons";
import FileViewerModal from "@/components/ui/FileViewerModal";
import ConfirmationModal from "@/components/ui/ConfirmationModal";
import DatePickerModal from "@/components/ui/DatePickerModal";
import TextInputModal from "@/components/ui/TextInputModal";
import ShipmentDiscrepanciesPanel from "@/components/discrepancies/ShipmentDiscrepanciesPanel";
import ShipmentItemDiscrepanciesPanel from "@/components/discrepancies/ShipmentItemDiscrepanciesPanel";
import { printBarcodes } from "@/utils/barcodePrint";
import toast from "react-hot-toast";
import { formatDate, formatDateTime } from "@/utils/dateUtils";
import { getShipmentStatusLabelForRole, getShipmentStatusColorForRole } from "../../../../../utils/roleStatusLabels";

export default function ShipmentViewPage() {
  const router = useRouter();
  const params = useParams();
  const shipmentId = Number(params.id);

  const [shipment, setShipment] = useState<Shipment | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [description, setDescription] = useState("");
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);
  const [expandedPallets, setExpandedPallets] = useState<Set<number>>(
    new Set()
  );

  // File viewer modal state
  const [showFileViewer, setShowFileViewer] = useState(false);
  const [documentToView, setDocumentToView] = useState<ShipmentDocument | null>(
    null
  );

  // Modal states
  const [showConfirmationModal, setShowConfirmationModal] = useState(false);
  const [showDatePickerModal, setShowDatePickerModal] = useState(false);
  const [showTextInputModal, setShowTextInputModal] = useState(false);
  const [pendingStatusUpdate, setPendingStatusUpdate] = useState<string | null>(
    null
  );
  const [modalConfig, setModalConfig] = useState<{
    title: string;
    description?: string;
    iconColor?: string;
    iconContainerColor?: string;
  }>({ title: "" });

  useEffect(() => {
    const fetchShipment = async () => {
      try {
        setLoading(true);
        const response = await shipmentService.getShipment(shipmentId);
        setShipment(response.data);
        setDescription(response.data.description || "");
        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]);

  const handleUpdateStatus = async (
    newStatus: string,
    additionalData?: any
  ) => {
    if (!shipment) return;

    try {
      setIsUpdatingStatus(true);
      const updateData: any = {
        status: newStatus,
        description: description,
        ...additionalData,
      };

      await shipmentService.updateShipment(shipment.id, updateData);

      // Update shipment state with proper field mapping
      const updatedShipment = {
        ...shipment,
        status: newStatus as any,
        description: description,
      };

      // Map additional data fields properly
      if (additionalData) {
        if (additionalData.dispatched_at) {
          updatedShipment.dispatchedAt = additionalData.dispatched_at;
        }
        if (additionalData.cancellation_reason) {
          updatedShipment.cancellationReason = additionalData.cancellation_reason;
        }
      }

      setShipment(updatedShipment);

      toast.success(
        `Shipment status updated to ${getShipmentStatusLabelForRole(newStatus, 'supplier')}`
      );
    } catch (error: any) {
      console.error("Failed to update shipment status:", error);
      toast.error("Failed to update shipment status. Please try again.");
    } finally {
      setIsUpdatingStatus(false);
      setPendingStatusUpdate(null);
    }
  };

  const handleDispatch = () => {
    setShowDatePickerModal(true);
  };

  const handleDispatchConfirm = (dispatchDate: string) => {
    handleUpdateStatus(ShipmentStatus.DISPATCHED, {
      dispatched_at: new Date(dispatchDate).toISOString(),
    });
  };

  const handleCancel = () => {
    setShowTextInputModal(true);
  };

  const handleCancelConfirm = (reason: string) => {
    handleUpdateStatus(ShipmentStatus.CANCELLED, {
      cancellation_reason: reason,
    });
  };

  const handleConfirmationConfirm = () => {
    if (pendingStatusUpdate) {
      handleUpdateStatus(pendingStatusUpdate);
    }
  };

  const handleDescriptionUpdate = async () => {
    if (!shipment) return;

    try {
      await shipmentService.updateShipment(shipment.id, {
        description: description,
      });

      setShipment({
        ...shipment,
        description: description,
      });

      toast.success("Description updated successfully");
    } catch (error: any) {
      console.error("Failed to update description:", error);
      toast.error("Failed to update description. Please try again.");
    }
  };

  const handleViewDocument = (document: ShipmentDocument) => {
    setDocumentToView(document);
    setShowFileViewer(true);
  };

  const handleCloseFileViewer = () => {
    setShowFileViewer(false);
    setDocumentToView(null);
  };

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

  const handlePrintPalletBarcodes = (shipmentPallet: any) => {
    if (!shipmentPallet.pallet.barcode) {
      toast.error("No barcode available for this pallet");
      return;
    }

    if (!shipment) {
      toast.error("Shipment data not available");
      return;
    }

    // At this point, shipment is guaranteed to be non-null
    const shipmentData = shipment;

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

    printBarcodes([palletBarcode], {
      title: `Pallet #${shipmentPallet.palletNumber} - ${shipmentData.shipmentNumber}`,
      orderNumber: shipmentData.shipmentNumber,
      quantity: 1,
    });
  };

  const handlePrintAllPalletBarcodes = () => {
    if (!shipment) {
      toast.error("Shipment data not available");
      return;
    }

    if (!shipment.shipmentPallets || shipment.shipmentPallets.length === 0) {
      toast.error("No pallets available to print");
      return;
    }

    const palletBarcodes = shipment.shipmentPallets
      .filter((shipmentPallet) => shipmentPallet.pallet.barcode)
      .map((shipmentPallet) => {
        const barcode = shipmentPallet.pallet.barcode!; // Non-null assertion since we filtered for it
        return {
          id: barcode.id,
          code: barcode.code,
          productName: `Pallet #${shipmentPallet.palletNumber}`,
          productImage: undefined,
        };
      });

    if (palletBarcodes.length === 0) {
      toast.error("No pallets with barcodes available to print");
      return;
    }

    printBarcodes(palletBarcodes, {
      title: `All Pallets - ${shipment.shipmentNumber}`,
      orderNumber: shipment.shipmentNumber,
      totalItems: shipment.shipmentPallets.length,
      totalBarcodes: palletBarcodes.length,
    });
  };


  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.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>
    );
  }

  if (!shipment) {
    return (
      <div className="bg-yellow-100 text-yellow-700 p-4 rounded-md">
        <p className="font-medium">Shipment not found</p>
        <p>The requested shipment does not exist or has been deleted.</p>
        <button
          onClick={() => router.push("/manufacturer")}
          className="mt-4 bg-white text-yellow-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back to Manufacturer
        </button>
      </div>
    );
  }

  return (
    <div className="manufacturer-shipment-detail-page">
      {/* 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 className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-8">
              <div>
                <span className="text-lg md:text-xl font-bold text-[#3997E0]">
                  Shipment ID{" "}
                </span>
                <span className="text-lg md:text-xl font-bold text-gray-800">
                  #{shipment.shipmentNumber}
                </span>
              </div>
              <div>
                <span className="text-lg md:text-xl font-bold text-[#3997E0]">
                  Date{" "}
                </span>
                <span className="text-lg md:text-xl font-bold text-gray-800">
                  {formatDateTime(shipment.shipmentDate)}
                </span>
              </div>
            </div>
            <div className="flex flex-col sm:flex-row gap-2 sm:gap-4 w-full sm:w-auto">
              {shipment.status === ShipmentStatus.DRAFT && (
                <>
                  <Link
                    href={`/manufacturer/shipments/${shipment.id}/edit`}
                    className="bg-[#092C4C] text-white py-2 px-4 rounded-xl hover:bg-[#092C4C]/80 flex items-center gap-2 justify-center"
                  >
                    <MdEdit className="h-5 w-5" />
                    <span className="hidden sm:inline">Edit</span>
                    <span className="sm:hidden">Edit</span>
                  </Link>
                  <button
                    onClick={handleDispatch}
                    disabled={isUpdatingStatus}
                    className="bg-[#3997E0] text-white py-2 px-4 sm:px-8 rounded-xl shadow hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed justify-center"
                  >
                    {isUpdatingStatus ? "Updating..." : "Dispatched"}
                  </button>
                </>
              )}

              {(shipment.status === ShipmentStatus.DISPATCHED ||
                shipment.status === ShipmentStatus.RECEIVED) && (
                <>
                  <button
                    onClick={handleCancel}
                    disabled={isUpdatingStatus}
                    className="bg-red-600 text-white py-2 px-4 sm:px-8 rounded-xl shadow hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed justify-center"
                  >
                    {isUpdatingStatus ? "Updating..." : "Cancel"}
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="m-4 md:m-6">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-4 lg:gap-6">
          {/* Left Column - Main Content */}
          <div className="lg:col-span-3 space-y-4 lg:space-y-6">
            {/* Pallets List */}
            {shipment.shipmentPallets &&
              shipment.shipmentPallets.length > 0 && (
                <div className="bg-white rounded-lg shadow">
                  <div className="p-6">
                    <div className="flex items-center justify-between mb-4">
                      <h2 className="text-lg font-semibold text-black">
                        Pallets
                      </h2>
                      <button
                        onClick={handlePrintAllPalletBarcodes}
                        className="bg-white text-gray-700 py-2 px-4 rounded-lg border border-gray-300 hover:bg-gray-50 flex items-center gap-2 text-sm"
                      >
                        <FiPrinter size={16} />
                        Print All Barcodes
                      </button>
                    </div>
                    <div className="space-y-3">
                      {shipment.shipmentPallets.map((shipmentPallet) => {
                        const isExpanded = expandedPallets.has(
                          shipmentPallet.id
                        );

                        // Group products by name
                        const productGroups: {
                          [key: string]: {
                            barcodes: string[];
                            quantity: number;
                          };
                        } = {};

                        shipmentPallet.shipmentPalletItems?.forEach((item) => {
                          const productName =
                            item.barcode?.product?.name ||
                            item.barcode?.purchaseOrderItem?.product?.name ||
                            "Unknown Product";
                          const barcode = item.barcode?.code || "";

                          if (!productGroups[productName]) {
                            productGroups[productName] = {
                              barcodes: [],
                              quantity: 0,
                            };
                          }
                          productGroups[productName].barcodes.push(barcode);
                          productGroups[productName].quantity += 1;
                        });

                        return (
                          <div
                            key={shipmentPallet.id}
                            className="bg-gray-50 rounded-lg border border-gray-200"
                          >
                            {/* Pallet Header */}
                            <div
                              className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
                              onClick={() =>
                                togglePalletExpansion(shipmentPallet.id)
                              }
                            >
                              <div className="flex items-center space-x-3">
                                <div className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">
                                  Pallet #{shipmentPallet.palletNumber}
                                </div>
                                {shipmentPallet.pallet.barcode && (
                                  <div className="text-sm text-gray-600">
                                    Barcode:{" "}
                                    {shipmentPallet.pallet.barcode.code}
                                  </div>
                                )}
                              </div>
                              <div className="flex items-center space-x-3">
                                <div className="text-sm text-gray-500">
                                  {shipmentPallet.shipmentPalletItems?.length ||
                                    0}{" "}
                                  items
                                </div>
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    handlePrintPalletBarcodes(shipmentPallet);
                                  }}
                                  className="bg-white text-gray-700 py-1 px-3 rounded-lg border border-gray-300 hover:bg-gray-50 flex items-center gap-1 text-sm"
                                >
                                  <FiPrinter size={14} />
                                  Print Barcodes
                                </button>
                                {isExpanded ? (
                                  <MdExpandLess
                                    className="text-gray-500"
                                    size={20}
                                  />
                                ) : (
                                  <MdExpandMore
                                    className="text-gray-500"
                                    size={20}
                                  />
                                )}
                              </div>
                            </div>

                            {/* Expanded Content */}
                            {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>
                        );
                      })}
                    </div>
                  </div>
                </div>
              )}

            {/* Discrepancies Panel — hidden when there are none */}
            <ShipmentDiscrepanciesPanel
              shipmentId={shipmentId}
              purchaseOrderLinkPath={(id) => `/manufacturer/manage-orders/${id}`}
            />

            {/* Item Discrepancies Panel — hidden when there are none */}
            <ShipmentItemDiscrepanciesPanel
              shipmentId={shipmentId}
              purchaseOrderLinkPath={(id) => `/manufacturer/manage-orders/${id}`}
            />

            {/* Documents List */}
            {shipment.documents && shipment.documents.length > 0 && (
              <div className="bg-violet-50 rounded-lg shadow">
                <div className="p-4">
                  <h2 className="text-lg font-semibold text-black mb-4">
                    Attachments
                  </h2>
                  {shipment.documents.map((document) => {
                    const isImage = /\.(jpe?g|png|gif|webp)$/i.test(
                      document.filename.toLowerCase()
                    );
                    const imageUrl = isImage ? document.url : null;

                    return (
                      <div
                        key={document.id}
                        className="bg-white rounded-lg shadow-sm p-4 flex items-center justify-between mb-3 last:mb-0"
                      >
                        <div className="flex items-center space-x-3 flex-1">
                          <div className="flex-shrink-0">
                            <div className="bg-gray-100 rounded-md p-2">
                              {getDocumentFileIcon(document.filename)}
                            </div>
                          </div>
                          <div className="flex-1 min-w-0">
                            <h4 className="text-sm font-medium text-gray-900 truncate">
                              {document.filename}
                            </h4>
                            <p className="text-xs text-gray-500 mt-1">
                              Uploaded on {formatDateTime(document.createdAt)}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2 flex-shrink-0">
                          <button
                            onClick={() => handleViewDocument(document)}
                            className="text-sm text-blue-500 hover:text-blue-700 font-medium"
                          >
                            View
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Description Section */}
            <div className="bg-white rounded-lg shadow">
              <div className="p-6">
                <h2 className="text-lg font-semibold text-gray-800 mb-3">
                  Description{" "}
                  <span className="text-sm font-normal text-gray-500">
                    (optional)
                  </span>
                </h2>
                <textarea
                  className={`w-full p-3 border border-gray-300 text-black rounded-md min-h-[120px] focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    shipment.status !== ShipmentStatus.DRAFT
                      ? "bg-gray-100 cursor-not-allowed"
                      : ""
                  }`}
                  placeholder="Enter shipment description..."
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  rows={5}
                  readOnly={shipment.status !== ShipmentStatus.DRAFT}
                  disabled={shipment.status !== ShipmentStatus.DRAFT}
                />
                {shipment.status === ShipmentStatus.DRAFT && (
                  <div className="mt-3 flex justify-end">
                    <button
                      onClick={handleDescriptionUpdate}
                      className="py-2 px-4 bg-[#3997E0] text-white rounded-md hover:bg-blue-700 text-sm"
                    >
                      Save Description
                    </button>
                  </div>
                )}
              </div>
            </div>

            {/* Cancel Reason Section - Only show if shipment is cancelled */}
            {shipment.status === ShipmentStatus.CANCELLED &&
              shipment.cancellationReason && (
                <div className="bg-red-50 rounded-lg shadow border border-red-200">
                  <div className="p-6">
                    <h2 className="text-lg font-semibold text-red-800 mb-3 flex items-center">
                      <FiX className="mr-2 text-red-600" />
                      Cancellation Reason
                    </h2>
                    <div className="bg-white p-3 border border-red-200 rounded-md">
                      <p className="text-gray-800 whitespace-pre-wrap">
                        {shipment.cancellationReason}
                      </p>
                    </div>
                  </div>
                </div>
              )}
          </div>

          {/* Right Column - Status Card */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow p-4 lg:p-6 lg:sticky lg:top-6">
              <h2 className="text-lg font-semibold text-gray-800 mb-4">
                Shipment Status
              </h2>

              {/* Current Status */}
              <div className="mb-6">
                <p className="text-sm text-gray-500 mb-2">Current Status</p>
                <span
                  className={`inline-block px-3 py-2 rounded-full text-sm font-medium ${getShipmentStatusColorForRole(getShipmentStatusLabelForRole(shipment.status, 'supplier'), 'supplier')}`}
                >
                  {getShipmentStatusLabelForRole(shipment.status, 'supplier')}
                </span>
              </div>

              {/* Shipment Details */}
              <div className="space-y-4 mb-6">
                <div>
                  <p className="text-sm text-gray-500">Shipment Number</p>
                  <p className="font-medium text-gray-800">
                    {shipment.shipmentNumber}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Shipment Date</p>
                  <p className="font-medium text-gray-800">
                    {formatDate(shipment.shipmentDate)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Created By</p>
                  <p className="font-medium text-gray-800">
                    {shipment.actor?.firstname} {shipment.actor?.lastname}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Created At</p>
                  <p className="font-medium text-gray-800">
                    {formatDateTime(shipment.createdAt)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Total Items</p>
                  <p className="font-medium text-gray-800">
                    {shipment.shipmentPallets?.reduce((total: number, sp: any) => total + (sp.shipmentPalletItems?.length || 0), 0) || 0}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* File Viewer Modal */}
        {showFileViewer && documentToView && (
          <FileViewerModal
            isOpen={showFileViewer}
            onClose={handleCloseFileViewer}
            file={{
              name: documentToView.filename,
              type: undefined,
              webViewLink:
                documentToView.url ||
                `https://drive.google.com/file/d/${documentToView.driveFileId}/view`,
              webContentLink: `https://drive.google.com/uc?id=${documentToView.driveFileId}&export=download`,
              driveFileId: documentToView.driveFileId,
            }}
          />
        )}

        {/* Confirmation Modal */}
        <ConfirmationModal
          isOpen={showConfirmationModal}
          onClose={() => setShowConfirmationModal(false)}
          onConfirm={handleConfirmationConfirm}
          title={modalConfig.title}
          description={modalConfig.description}
          iconColor={modalConfig.iconColor}
          iconContainerColor={modalConfig.iconContainerColor}
          confirmText="Yes, Confirm"
          cancelText="Cancel"
        />

        {/* Date Picker Modal */}
        <DatePickerModal
          isOpen={showDatePickerModal}
          onClose={() => setShowDatePickerModal(false)}
          onConfirm={handleDispatchConfirm}
          title="Select Dispatch Date"
          description="Please select the date when this shipment was dispatched."
          confirmText="Dispatch"
          cancelText="Cancel"
        />

        {/* Text Input Modal */}
        <TextInputModal
          isOpen={showTextInputModal}
          onClose={() => setShowTextInputModal(false)}
          onConfirm={handleCancelConfirm}
          title="Cancel Shipment"
          description="Please provide a reason for cancelling this shipment."
          placeholder="Enter cancellation reason..."
          confirmText="Cancel Shipment"
          cancelText="Keep Shipment"
          required={true}
          multiline={true}
        />
      </div>
    </div>
  );
}
