"use client";

import { useState } from "react";
import Button from "@/components/ui/Button";
import {
  DatosRecibo,
  isMobile,
  abrirPassPrnt,
  generarEtiquetasPdf,
  compartirEtiquetaPdfPendiente,
  ShareResult,
} from "@/lib/print";

interface PrintButtonProps {
  mode: "etiqueta" | "recibo";
  recibo?: DatosRecibo;
  label?: string;
  onFallback?: () => void;
  className?: string;
  fullWidth?: boolean;
  variant?: "primary" | "secondary" | "outline" | "ghost" | "danger";
  size?: "sm" | "md" | "lg";
  onResult?: (
    result: ShareResult | { printed: true } | { error: string }
  ) => void;
  disabled?: boolean;
}

export default function PrintButton({
  mode,
  recibo,
  label = "🖨️ IMPRIMIR",
  onFallback,
  className = "",
  fullWidth = false,
  variant = "primary",
  size = "md",
  onResult,
  disabled: disabledProp = false,
}: PrintButtonProps) {
  const [loading, setLoading] = useState(false);
  const [mensaje, setMensaje] = useState<string | null>(null);
  const [pdfReady, setPdfReady] = useState(false);

  async function generarPdfEtiqueta() {
    setMensaje(null);
    setLoading(true);

    try {
      const result = await generarEtiquetasPdf(
        "etiquetas-hce-4x6.pdf"
      );

      if (result.error) {
        onResult?.({ error: result.error });
        setMensaje(`Error: ${result.error}`);
        setPdfReady(false);
      } else {
        setPdfReady(true);
        setMensaje(
          "PDF listo. Toca COMPARTIR / GUARDAR PDF."
        );
      }
    } catch (err: any) {
      const result = {
        error: err?.message || "Error generando PDF.",
      };

      onResult?.(result);
      setMensaje(result.error);
      setPdfReady(false);
    } finally {
      setLoading(false);
    }
  }

  async function compartirPdfEtiqueta() {
    setMensaje(null);

    try {
      const result = await compartirEtiquetaPdfPendiente();

      onResult?.(result);

      if (result.shared) {
        setMensaje("PDF compartido correctamente.");
      } else if (result.downloaded) {
        setMensaje(
          "Se abrió el PDF. Guárdalo o compártelo con MUNBYN Print."
        );
      } else if (result.cancelled) {
        setMensaje("Compartir cancelado.");
      } else if (result.error) {
        setMensaje(`Error: ${result.error}`);
      }
    } catch (err: any) {
      const result = {
        error: err?.message || "Error compartiendo PDF.",
      };

      onResult?.(result);
      setMensaje(result.error);
    }
  }

  function handleClick() {
    setMensaje(null);

    const mobile = isMobile();

    if (mode === "recibo") {
      if (!recibo) {
        const err = {
          error: "Faltan los datos del recibo.",
        };

        onResult?.(err);
        return;
      }

      if (mobile) {
        abrirPassPrnt(recibo);

        const result = {
          printed: true as const,
        };

        onResult?.(result);
        setMensaje(
          "Se abrió Star PassPRNT para imprimir."
        );
        return;
      }

      onFallback?.();
      return;
    }

    if (mode === "etiqueta") {
      if (mobile) {
        void generarPdfEtiqueta();
        return;
      }

      onFallback?.();
    }
  }

  return (
    <div
      className={`inline-flex flex-col ${
        fullWidth ? "w-full" : ""
      }`}
    >
      <Button
        type="button"
        variant={variant}
        size={size}
        fullWidth={fullWidth}
        className={className}
        disabled={loading || disabledProp}
        onClick={handleClick}
      >
        {loading
          ? "Preparando…"
          : pdfReady
            ? "PDF LISTO"
            : label}
      </Button>

      {pdfReady && (
        <Button
          type="button"
          variant="secondary"
          size={size}
          fullWidth={fullWidth}
          className={`mt-2 ${className}`}
          onClick={compartirPdfEtiqueta}
        >
          COMPARTIR / GUARDAR PDF
        </Button>
      )}

      {mensaje && (
        <span className="mt-2 text-center text-[10px] font-medium text-[var(--text-muted)]">
          {mensaje}
        </span>
      )}
    </div>
  );
}