"use client";

import React, { useEffect, useRef } from "react";
import { FiPrinter, FiX } from "react-icons/fi";
import JsBarcode from "jsbarcode";
import {
  printBarcodes,
  BarcodeData as UtilityBarcodeData,
} from "../../utils/barcodePrint";

interface BarcodeData {
  id: number;
  code: string;
  productName: string;
  productImage?: string;
}

interface BarcodeViewerModalProps {
  isOpen: boolean;
  onClose: () => void;
  orderId: string;
  barcodes: BarcodeData[];
  title?: string;
}

export default function BarcodeViewerModal({
  isOpen,
  onClose,
  orderId,
  barcodes,
  title,
}: BarcodeViewerModalProps) {
  // Handle ESC key to close modal
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("keydown", handleKeyDown);
    }

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const handlePrint = () => {
    // Transform barcodes to match the utility interface
    const utilityBarcodes: UtilityBarcodeData[] = barcodes.map((barcode) => ({
      id: barcode.id,
      code: barcode.code,
      productName: barcode.productName,
      productImage: barcode.productImage,
    }));

    // Determine print title and options
    const groupedBarcodes = barcodes.reduce((acc, barcode) => {
      if (!acc[barcode.productName]) {
        acc[barcode.productName] = [];
      }
      acc[barcode.productName].push(barcode);
      return acc;
    }, {} as Record<string, BarcodeData[]>);

    const productNames = Object.keys(groupedBarcodes);

    let printTitle = title;
    if (!printTitle) {
      if (productNames.length === 1) {
        printTitle = `Barcodes for ${productNames[0]}`;
      } else {
        printTitle = `All Barcodes - Order #${orderId}`;
      }
    }

    // Use the barcode print utility
    printBarcodes(utilityBarcodes, {
      title: printTitle,
      orderNumber: orderId,
      totalBarcodes: barcodes.length,
      totalItems: productNames.length,
    });
  };

  // Component to generate barcode image
  const BarcodeImage = ({ code }: { code: string }) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);

    useEffect(() => {
      if (canvasRef.current && code) {
        try {
          // Use CODE128 format for all barcodes
          let barcodeFormat = "CODE128";

          JsBarcode(canvasRef.current, code, {
            format: barcodeFormat,
            width: window.innerWidth < 640 ? 1.8 : 2.5, // Smaller width on mobile
            height: window.innerWidth < 640 ? 80 : 100, // Smaller height on mobile
            displayValue: true,
            fontSize: window.innerWidth < 640 ? 9 : 11, // Smaller font on mobile
            margin: window.innerWidth < 640 ? 2 : 4, // Smaller margin on mobile
            background: "#ffffff",
            lineColor: "#000000",
            textAlign: "center",
            textPosition: "bottom",
            textMargin: 2,
          });
        } catch (error) {
          console.error("Failed to generate barcode:", error);
        }
      }
    }, [code]);

    return (
      <div className="flex flex-col items-center space-y-2">
        <div className="bg-white border-2 border-gray-300 p-2 sm:p-4 rounded-lg">
          <canvas
            ref={canvasRef}
            style={{
              imageRendering: "crisp-edges",
              maxWidth: "100%",
              height: "auto",
            }}
          ></canvas>
        </div>
        <div className="text-xs sm:text-sm text-gray-500 break-all px-2">
          Barcode: {code}
        </div>
      </div>
    );
  };

  const renderBarcode = (code: string) => {
    return <BarcodeImage code={code} />;
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-2 sm:p-4">
      <div className="bg-white rounded-lg max-w-4xl w-full max-h-[95vh] sm:max-h-[90vh] flex flex-col">
        {/* Fixed Header */}
        <div className="border-b bg-white rounded-t-lg flex-shrink-0">
          {/* Desktop Header */}
          <div className="hidden sm:flex items-center justify-between p-6">
            <div className="flex items-center space-x-2">
              <span className="text-lg font-medium text-gray-700">
                Previewing Barcodes :
              </span>
              <span className="text-lg font-medium text-[#3997E0]">
                Order ID #{orderId}
              </span>
              <span className="text-lg font-medium text-gray-700">
                --- {title || `${barcodes.length} Items`}
              </span>
            </div>
            <div className="flex items-center space-x-4">
              <button
                onClick={handlePrint}
                className="bg-[#3997E0] text-white px-6 py-2 rounded-lg flex items-center space-x-2 hover:bg-blue-700 transition-colors"
              >
                <FiPrinter size={16} />
                <span>Print Barcodes</span>
              </button>
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600 transition-colors"
                title="Close (ESC)"
              >
                <FiX size={24} />
              </button>
            </div>
          </div>

          {/* Mobile Header */}
          <div className="sm:hidden p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium text-gray-700">
                  Previewing Barcodes
                </div>
                <div className="text-sm font-medium text-[#3997E0] truncate">
                  Order #{orderId}
                </div>
                {title && (
                  <div className="text-xs text-gray-500 truncate">{title}</div>
                )}
              </div>
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600 transition-colors p-2 touch-manipulation"
                title="Close"
              >
                <FiX size={20} />
              </button>
            </div>

            <button
              onClick={handlePrint}
              className="w-full bg-[#3997E0] text-white py-3 px-4 rounded-lg flex items-center justify-center space-x-2 hover:bg-blue-700 transition-colors touch-manipulation"
            >
              <FiPrinter size={18} />
              <span>Print All Barcodes</span>
            </button>
          </div>
        </div>

        {/* Scrollable Content */}
        <div className="p-3 sm:p-6 overflow-y-auto flex-1">
          {(() => {
            // Group barcodes by product name for better organization
            const groupedBarcodes = barcodes.reduce((acc, barcode) => {
              if (!acc[barcode.productName]) {
                acc[barcode.productName] = [];
              }
              acc[barcode.productName].push(barcode);
              return acc;
            }, {} as Record<string, BarcodeData[]>);

            const productNames = Object.keys(groupedBarcodes);

            if (barcodes.length === 1) {
              // Single barcode view
              const barcode = barcodes[0];
              return (
                <div className="bg-[#e0f2fe] rounded-lg p-4 sm:p-8 text-center">
                  <h2 className="text-lg sm:text-2xl font-semibold text-[#3997E0] mb-4 sm:mb-8 px-2">
                    Barcode For {barcode.productName}
                  </h2>

                  <div className="bg-white rounded-lg p-4 sm:p-8 inline-block shadow-sm max-w-full">
                    <div className="text-center">
                      {renderBarcode(barcode.code)}
                    </div>

                    <div className="mt-4 sm:mt-6 flex items-center justify-center space-x-2">
                      <div className="w-6 h-6 sm:w-8 sm:h-8 bg-[#0ea5e9] rounded-full flex items-center justify-center">
                        <span className="text-white text-xs font-bold">S</span>
                      </div>
                      <span className="text-[#0ea5e9] font-semibold text-sm sm:text-base">
                        springaqua
                      </span>
                    </div>
                  </div>
                </div>
              );
            } else {
              // Multiple barcodes view - clean and simple
              return (
                <div className="bg-[#e0f2fe] rounded-lg p-4 sm:p-8">
                  <h2 className="text-lg sm:text-2xl font-semibold text-[#3997E0] text-center mb-4 sm:mb-8 px-2">
                    {productNames.length === 1
                      ? `All Barcodes for ${productNames[0]}`
                      : `All Barcodes for Order #${orderId}`}
                  </h2>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-8">
                    {barcodes.map((barcode, index) => (
                      <div key={barcode.id} className="text-center">
                        <div className="bg-white rounded-lg p-4 sm:p-6 shadow-sm">
                          <div className="mb-3 sm:mb-4">
                            <h3 className="text-base sm:text-lg font-semibold text-[#3997E0] mb-1 px-1">
                              {barcode.productName}
                            </h3>
                            <p className="text-xs sm:text-sm text-gray-600">
                              Item #{index + 1}
                            </p>
                          </div>

                          <div className="mb-4 sm:mb-6 overflow-x-auto">
                            {renderBarcode(barcode.code)}
                          </div>

                          <div className="flex items-center justify-center space-x-2">
                            <div className="w-5 h-5 sm:w-6 sm:h-6 bg-[#0ea5e9] rounded-full flex items-center justify-center">
                              <span className="text-white text-xs font-bold">
                                S
                              </span>
                            </div>
                            <span className="text-[#0ea5e9] font-medium text-xs sm:text-sm">
                              springaqua
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              );
            }
          })()}
        </div>
      </div>
    </div>
  );
}
