"use client";

import React, { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
import {
  MdQrCodeScanner,
  MdEdit,
  MdExpandMore,
  MdExpandLess,
  MdReportProblem,
  MdRemoveCircleOutline,
  MdUndo,
} from "react-icons/md";
import { FiX } from "react-icons/fi";
import { warehouseShipmentService, itemDiscrepanciesService } from "@/services/api";
import { Shipment, ShipmentStatus, ShipmentDocument } from "@/types/shipment";
import { ShipmentPalletItemCondition, PalletReceivedCondition } from "@/types/pallet";
import { getDocumentFileIcon } from "@/utils/fileIcons";
import FileViewerModal from "@/components/ui/FileViewerModal";
import MarkDamageModal from "@/components/ui/MarkDamageModal";
import ConfirmationModal from "@/components/ui/ConfirmationModal";
import ShipmentDiscrepanciesPanel from "@/components/discrepancies/ShipmentDiscrepanciesPanel";
import ShipmentItemDiscrepanciesPanel from "@/components/discrepancies/ShipmentItemDiscrepanciesPanel";
import { useAuth } from "@/contexts/AuthContext";
import toast from "react-hot-toast";
import { formatDate, formatDateTime } from "@/utils/dateUtils";
import { getShipmentStatusLabelForRole, getShipmentStatusColorForRole } from "../../../../../utils/roleStatusLabels";

export default function WarehouseShipmentViewPage() {
  const router = useRouter();
  const params = useParams();
  const shipmentId = Number(params.id);
  const { isAdmin } = useAuth();

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

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

  // Damage viewer modal state
  const [showDamageModal, setShowDamageModal] = useState(false);
  const [damageDetails, setDamageDetails] = useState<{
    productName: string;
    barcodeNumber: string;
    description: string;
    images: string[];
  } | null>(null);
  const [loadingDamageReport, setLoadingDamageReport] = useState(false);

  // Item-level discrepancy reporting state (post-receipt, on-pallet-open)
  type ItemReportTarget = {
    palletItemId: number;
    productName: string;
    barcode: string;
  };
  const [itemDamageTarget, setItemDamageTarget] =
    useState<ItemReportTarget | null>(null);
  const [itemMissingTarget, setItemMissingTarget] =
    useState<ItemReportTarget | null>(null);
  const [itemClearTarget, setItemClearTarget] =
    useState<ItemReportTarget | null>(null);
  const [isSubmittingItemReport, setIsSubmittingItemReport] = useState(false);

  useEffect(() => {
    const fetchShipment = async () => {
      try {
        setLoading(true);
        const response =
          await warehouseShipmentService.getShipmentWithPurchaseOrderDetails(
            shipmentId
          );
        setShipment(response.data);
        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 handleViewDocument = (document: ShipmentDocument) => {
    setDocumentToView(document);
    setShowFileViewer(true);
  };

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

  const handleScanShipment = () => {
    router.push(`/warehouses/shipments/${shipmentId}/scan`);
  };

  const handleViewDamageReport = async (
    productName: string,
    barcodeCode: string
  ) => {
    try {
      setLoadingDamageReport(true);
      const response = await warehouseShipmentService.getDamageReport(
        shipmentId,
        barcodeCode
      );
      const damageReport = response.data;

      setDamageDetails({
        productName,
        barcodeNumber: barcodeCode,
        description: damageReport.description || "",
        images: damageReport.images || [],
      });
      setShowDamageModal(true);
    } catch (error: any) {
      console.error("Failed to load damage report:", error);
      toast.error("Failed to load damage report details");
    } finally {
      setLoadingDamageReport(false);
    }
  };

  const handleCloseDamageModal = () => {
    setShowDamageModal(false);
    setDamageDetails(null);
  };

  const refetchShipment = async () => {
    try {
      const response =
        await warehouseShipmentService.getShipmentWithPurchaseOrderDetails(
          shipmentId
        );
      setShipment(response.data);
    } catch (err) {
      console.error("Failed to refresh shipment", err);
    }
  };

  const handleReportItemDamaged = async (
    description: string,
    images: string[]
  ) => {
    if (!itemDamageTarget) return;
    try {
      setIsSubmittingItemReport(true);
      await itemDiscrepanciesService.reportDamaged(
        itemDamageTarget.palletItemId,
        description,
        images
      );
      toast.success("Item reported as damaged.");
      setItemDamageTarget(null);
      await refetchShipment();
    } catch (err: any) {
      toast.error(err.response?.data?.message || "Failed to report damaged item.");
    } finally {
      setIsSubmittingItemReport(false);
    }
  };

  const handleConfirmItemMissing = async () => {
    if (!itemMissingTarget) return;
    try {
      await itemDiscrepanciesService.reportMissing(
        itemMissingTarget.palletItemId
      );
      toast.success("Item reported as missing.");
      setItemMissingTarget(null);
      await refetchShipment();
    } catch (err: any) {
      toast.error(err.response?.data?.message || "Failed to report missing item.");
    }
  };

  const handleConfirmItemClear = async () => {
    if (!itemClearTarget) return;
    try {
      await itemDiscrepanciesService.clear(itemClearTarget.palletItemId);
      toast.success("Item marked OK and stock restored.");
      setItemClearTarget(null);
      await refetchShipment();
    } catch (err: any) {
      toast.error(err.response?.data?.message || "Failed to clear item.");
    }
  };

  const itemConditionStyles = (cond: ShipmentPalletItemCondition) => {
    if (cond === ShipmentPalletItemCondition.DAMAGED) {
      return { label: "Damaged", className: "bg-amber-100 text-amber-800" };
    }
    if (cond === ShipmentPalletItemCondition.MISSING) {
      return { label: "Missing", className: "bg-red-100 text-red-800" };
    }
    return { label: "OK", className: "bg-green-100 text-green-800" };
  };

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

  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("/warehouses/shipments")}
          className="mt-4 bg-white text-red-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back to Shipments
        </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("/warehouses/shipments")}
          className="mt-4 bg-white text-yellow-700 py-2 px-4 rounded-md hover:bg-gray-100"
        >
          Back to Shipments
        </button>
      </div>
    );
  }

  return (
    <div className="warehouse-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 gap-4">
              {shipment.status === ShipmentStatus.DISPATCHED && (
                <button
                  onClick={handleScanShipment}
                  className="bg-[#3997E0] text-white py-2 px-4 md:px-8 rounded-xl shadow hover:bg-blue-700 flex items-center gap-2 w-full sm:w-auto justify-center sm:justify-start"
                >
                  <MdQrCodeScanner className="h-5 w-5" />
                  <span className="hidden sm:inline">Scan Shipment</span>
                  <span className="sm:hidden">Scan</span>
                </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="mb-4">
                      <h2 className="text-lg font-semibold text-black">
                        Pallets
                      </h2>
                    </div>
                    <div className="space-y-3">
                      {shipment.shipmentPallets.map((shipmentPallet) => {
                        const isExpanded = expandedPallets.has(
                          shipmentPallet.id
                        );

                        // Item-level reporting is allowed for received shipments
                        // on pallets whose condition is ok or damaged. Missing
                        // pallets and pending pallets cannot host item reports.
                        const palletAllowsReporting =
                          shipment.status === ShipmentStatus.RECEIVED &&
                          (shipmentPallet.receivedCondition ===
                            PalletReceivedCondition.OK ||
                            shipmentPallet.receivedCondition ===
                              PalletReceivedCondition.DAMAGED);
                        const canReportOnThisPallet =
                          isAdmin() && palletAllowsReporting;

                        // Group items by product name for visual structure but
                        // keep per-item references so we can render a button per
                        // barcode.
                        const productGroups: Record<
                          string,
                          Array<(typeof shipmentPallet.shipmentPalletItems)[number]>
                        > = {};
                        shipmentPallet.shipmentPalletItems?.forEach((item) => {
                          const productName =
                            (item.barcode as any)?.product?.name ||
                            (item.barcode as any)?.purchaseOrderItem?.product
                              ?.name ||
                            "Unknown Product";
                          if (!productGroups[productName]) {
                            productGroups[productName] = [];
                          }
                          productGroups[productName].push(item);
                        });

                        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>
                                {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, items]) => (
                                      <div
                                        key={productName}
                                        className="bg-white rounded-md border border-gray-200 p-3"
                                      >
                                        <div className="flex items-center justify-between mb-2">
                                          <h5 className="text-sm font-medium text-gray-900">
                                            {productName}
                                          </h5>
                                          <div className="text-sm font-medium text-blue-600 bg-blue-50 px-2 py-1 rounded">
                                            x {items.length}
                                          </div>
                                        </div>
                                        <div className="space-y-1">
                                          {items.map((item) => {
                                            const cond =
                                              item.itemCondition ||
                                              ShipmentPalletItemCondition.OK;
                                            const styles =
                                              itemConditionStyles(cond);
                                            const isOk =
                                              cond ===
                                              ShipmentPalletItemCondition.OK;
                                            const target = {
                                              palletItemId: item.id,
                                              productName,
                                              barcode: item.barcode?.code || "",
                                            };
                                            return (
                                              <div
                                                key={item.id}
                                                className="flex items-center justify-between text-xs text-gray-600 bg-gray-50 rounded px-2 py-1.5"
                                              >
                                                <div className="flex items-center gap-2 flex-wrap">
                                                  <span className="font-mono text-gray-700">
                                                    {item.barcode?.code || "—"}
                                                  </span>
                                                  <span
                                                    className={`px-1.5 py-0.5 rounded-full text-[10px] font-semibold ${styles.className}`}
                                                  >
                                                    {styles.label}
                                                  </span>
                                                </div>
                                                {canReportOnThisPallet && (
                                                  <div className="flex items-center gap-1">
                                                    {isOk ? (
                                                      <>
                                                        <button
                                                          onClick={() =>
                                                            setItemDamageTarget(
                                                              target
                                                            )
                                                          }
                                                          className="inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] text-amber-700 hover:bg-amber-50 rounded"
                                                          title="Report as damaged"
                                                        >
                                                          <MdReportProblem
                                                            size={12}
                                                          />
                                                          Damaged
                                                        </button>
                                                        <button
                                                          onClick={() =>
                                                            setItemMissingTarget(
                                                              target
                                                            )
                                                          }
                                                          className="inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] text-red-700 hover:bg-red-50 rounded"
                                                          title="Report as missing"
                                                        >
                                                          <MdRemoveCircleOutline
                                                            size={12}
                                                          />
                                                          Missing
                                                        </button>
                                                      </>
                                                    ) : !item.itemDiscrepancyResolvedAt ? (
                                                      <button
                                                        onClick={() =>
                                                          setItemClearTarget(
                                                            target
                                                          )
                                                        }
                                                        className="inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] text-green-700 hover:bg-green-50 rounded"
                                                        title="Mark OK and restore stock"
                                                      >
                                                        <MdUndo size={12} />
                                                        Mark OK
                                                      </button>
                                                    ) : null}
                                                  </div>
                                                )}
                                              </div>
                                            );
                                          })}
                                        </div>
                                      </div>
                                    )
                                  )}
                                </div>
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
              )}

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

            {/* Item Discrepancies Panel — hidden when there are none */}
            <ShipmentItemDiscrepanciesPanel
              shipmentId={shipmentId}
              purchaseOrderLinkPath={(id) => `/purchase-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">
                          {isImage && imageUrl ? (
                            <img
                              src={imageUrl}
                              alt={document.filename}
                              className="w-12 h-12 object-cover rounded-md mr-4 flex-shrink-0"
                            />
                          ) : (
                            getDocumentFileIcon(document.filename)
                          )}
                          <div>
                            <h3 className="font-semibold text-sm text-gray-800">
                              {document.filename}
                            </h3>
                            <p className="text-xs text-gray-500">
                              {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 */}
            {shipment.description && (
              <div className="bg-white rounded-lg shadow">
                <div className="p-6">
                  <h2 className="text-lg font-semibold text-gray-800 mb-3">
                    Description
                  </h2>
                  <div className="w-full p-3 border border-gray-300 text-black rounded-md min-h-[120px] bg-gray-100">
                    <p className="whitespace-pre-wrap">
                      {shipment.description}
                    </p>
                  </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, 'admin'), 'admin')}`}
                >
                  {getShipmentStatusLabelForRole(shipment.status, 'admin')}
                </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 Pallets</p>
                  <p className="font-medium text-gray-800">
                    {shipment.shipmentPallets?.length || 0}
                  </p>
                </div>
                {shipment.dispatchedAt && (
                  <div>
                    <p className="text-sm text-gray-500">Dispatched At</p>
                    <p className="font-medium text-gray-800">
                      {formatDateTime(shipment.dispatchedAt)}
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Damage Viewer Modal */}
        {damageDetails && (
          <MarkDamageModal
            isOpen={showDamageModal}
            onClose={handleCloseDamageModal}
            onSubmit={() => {}} // Not used in read-only mode
            productName={damageDetails.productName}
            barcodeNumber={damageDetails.barcodeNumber}
            isReadOnly={true}
            initialDescription={damageDetails.description}
            initialImages={damageDetails.images}
          />
        )}

        {/* Item-level Report Damaged Modal */}
        {itemDamageTarget && (
          <MarkDamageModal
            isOpen={true}
            onClose={() => setItemDamageTarget(null)}
            onSubmit={handleReportItemDamaged}
            productName={itemDamageTarget.productName}
            barcodeNumber={itemDamageTarget.barcode}
            isSubmitting={isSubmittingItemReport}
          />
        )}

        {/* Item-level Report Missing Confirmation */}
        {itemMissingTarget && (
          <ConfirmationModal
            isOpen={true}
            onClose={() => setItemMissingTarget(null)}
            onConfirm={handleConfirmItemMissing}
            title="Mark Item Missing"
            description={`Mark ${itemMissingTarget.productName} (barcode ${
              itemMissingTarget.barcode || "—"
            }) as missing? Stock will be reduced by 1.`}
            iconColor="#DC2626"
            iconContainerColor="#FEE2E2"
            confirmText="Yes, Mark Missing"
            cancelText="Cancel"
            autoCloseOnConfirm={false}
          />
        )}

        {/* Item-level Mark OK (clear) Confirmation */}
        {itemClearTarget && (
          <ConfirmationModal
            isOpen={true}
            onClose={() => setItemClearTarget(null)}
            onConfirm={handleConfirmItemClear}
            title="Mark Item OK"
            description={`Revert ${itemClearTarget.productName} (barcode ${
              itemClearTarget.barcode || "—"
            }) back to OK and restore stock by 1?`}
            iconColor="#10B981"
            iconContainerColor="#D1FAE5"
            confirmText="Mark OK"
            cancelText="Cancel"
            autoCloseOnConfirm={false}
          />
        )}

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