import { useRef, useState, useEffect } from "react";
import Barcode from "react-barcode";
import { Plus, Printer } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

interface BarcodeGeneratorProps {
  barcode: string;
  sku: string;
  productName: string;
  onGenerate: () => void;
}

export function BarcodeGenerator({ barcode, sku, productName, onGenerate }: BarcodeGeneratorProps) {
  const printRef = useRef<HTMLDivElement>(null);
  const [modalOpen, setModalOpen] = useState(false);

  function handlePrint() {
    if (!barcode) {
      toast.error("Nenhum código de barras para imprimir.");
      return;
    }

    const printContents = printRef.current?.innerHTML;
    if (!printContents) return;

    const printHtml = `<!doctype html>
      <html lang="pt-BR">
        <head>
          <meta charset="utf-8" />
          <title>Imprimir Etiqueta</title>
          <style>
            @page {
              size: auto;
              margin: 0;
            }
            body { 
              font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
              margin: 0;
              padding: 0;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              width: 100vw;
              height: 100vh;
              overflow: hidden;
              background: white;
              color: black;
            }
            .label-container {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              text-align: center;
              padding: 10px;
            }
            .product-name {
              font-weight: 700;
              font-size: 14px;
              margin-bottom: 8px;
              text-transform: uppercase;
              max-width: 200px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              color: inherit;
            }
            .sku {
              font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
              font-size: 12px;
              margin-top: 8px;
              color: inherit;
            }
            @media print {
              html, body {
                width: 100%;
                height: 100%;
              }
            }
          </style>
        </head>
        <body>
          ${printContents}
        </body>
      </html>`;

    const iframe = document.createElement("iframe");
    iframe.setAttribute("aria-hidden", "true");
    iframe.style.position = "fixed";
    iframe.style.right = "0";
    iframe.style.bottom = "0";
    iframe.style.width = "0";
    iframe.style.height = "0";
    iframe.style.border = "0";
    iframe.style.opacity = "0";
    iframe.style.pointerEvents = "none";

    const cleanup = () => {
      iframe.onload = null;
      if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
    };

    iframe.onload = () => {
      const frameWindow = iframe.contentWindow;
      if (!frameWindow) {
        cleanup();
        return;
      }
      const onAfterPrint = () => {
        frameWindow.removeEventListener("afterprint", onAfterPrint);
        cleanup();
      };
      frameWindow.addEventListener("afterprint", onAfterPrint);
      window.setTimeout(() => {
        frameWindow.focus();
        frameWindow.print();
      }, 120);
      window.setTimeout(cleanup, 15000); // Fail-safe cleanup
    };

    iframe.srcdoc = printHtml;
    document.body.appendChild(iframe);
  }

  return (
    <div className="flex flex-col gap-2 w-full mt-2">
      <div className="flex items-center gap-2">
        <Button 
          type="button" 
          variant="outline" 
          size="sm" 
          onClick={onGenerate}
          icon={<Plus size={14} />}
          className="text-xs"
        >
          {barcode ? "Gerar Novo" : "Gerar Código"}
        </Button>
        {barcode && (
          <Button 
            type="button" 
            variant="outline" 
            size="sm" 
            onClick={() => {
              // Force body pointer events cleanup just in case
              document.body.style.pointerEvents = 'auto';
              setModalOpen(true);
            }}
            icon={<Printer size={14} />}
            className="text-xs"
          >
            Imprimir Etiqueta
          </Button>
        )}
      </div>

      {modalOpen && (
        <div 
          className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4" 
          onClick={() => {
            setModalOpen(false);
            document.body.style.pointerEvents = 'auto';
          }}
        >
          <div 
            className="w-full max-w-xs bg-white border rounded-xl shadow-2xl flex flex-col overflow-hidden" 
            onClick={(e) => e.stopPropagation()}
          >
            <div className="p-4 border-b text-center font-semibold text-lg text-zinc-800">
              Etiqueta do Produto
            </div>
            
            <div className="flex flex-col items-center justify-center p-8 bg-white">
              <div ref={printRef} className="label-container flex flex-col justify-center items-center">
                <div className="product-name font-bold text-sm mb-2 uppercase max-w-[200px] truncate text-center" style={{ color: 'black' }}>
                  {productName || "Produto"}
                </div>
                <Barcode 
                  value={barcode || "0000"} 
                  width={2} 
                  height={40} 
                  fontSize={12} 
                  margin={0} 
                  displayValue={true} 
                />
                {sku && <div className="sku text-xs mt-2 text-center font-mono" style={{ color: 'black' }}>SKU: {sku}</div>}
              </div>
            </div>

            <div className="p-4 border-t flex items-center justify-center gap-2 bg-zinc-50">
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  setModalOpen(false);
                  document.body.style.pointerEvents = 'auto';
                }}
                className="w-full"
              >
                Cancelar
              </Button>
              <Button
                type="button"
                onClick={handlePrint}
                className="w-full border-[var(--ks-color-primary)] bg-[var(--ks-color-primary)] text-white hover:bg-[var(--ks-color-primary-dark)]"
                icon={<Printer size={16} />}
              >
                Imprimir
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
