"use client";

import { useState, useCallback } from "react";
import { cn } from "@/lib/utils";
import { exportMultiPageCanvasToPDF } from "@/lib/pdf/generate-pdf";
import type { CanvasTemplate } from "@/lib/types";

interface ExportButtonProps {
  canvas: CanvasTemplate;
  className?: string;
  variant?: "default" | "compact";
  /** Reference to the canvas element to export */
  canvasRef?: React.RefObject<HTMLElement>;
}

export function ExportButton({
  canvas,
  className,
  variant = "default",
  canvasRef
}: ExportButtonProps) {
  const [isExporting, setIsExporting] = useState(false);

  const handleExport = useCallback(async () => {
    setIsExporting(true);

    try {
      // Find the canvas element
      let canvasElement: HTMLElement | null = null;

      if (canvasRef?.current) {
        canvasElement = canvasRef.current;
      } else {
        // Try to find the canvas element by looking for the data attribute
        canvasElement = document.querySelector('[data-canvas-id="' + canvas.id + '"]') as HTMLElement;

        if (!canvasElement) {
          // Fallback: find the main canvas container
          canvasElement = document.querySelector('.bg-white.border-2.border-black') as HTMLElement;
        }
      }

      if (!canvasElement) {
        throw new Error("Impossible de trouver l'élément canevas à exporter.");
      }

      // Export to PDF - this handles both single and multi-page canvases
      // For multi-page canvases, it will find all [data-page-index] elements
      await exportMultiPageCanvasToPDF(canvasElement, canvas, {
        format: "A3",
        orientation: "landscape",
      });

    } catch (error) {
      console.error("Export failed:", error);
      alert(
        error instanceof Error
          ? error.message
          : "L'export PDF a échoué. Veuillez réessayer."
      );
    } finally {
      setIsExporting(false);
    }
  }, [canvas, canvasRef]);

  if (variant === "compact") {
    return (
      <button
        onClick={handleExport}
        disabled={isExporting}
        className={cn(
          "px-3 py-1.5 text-sm font-medium rounded-lg transition-colors",
          "bg-gray-100 text-gray-700 hover:bg-gray-200",
          "disabled:opacity-50 disabled:cursor-not-allowed",
          className
        )}
        title="Exporter en PDF A3"
      >
        {isExporting ? "Export..." : "PDF"}
      </button>
    );
  }

  return (
    <button
      onClick={handleExport}
      disabled={isExporting}
      className={cn(
        "px-4 py-2 text-sm font-medium rounded-lg transition-colors flex items-center gap-2",
        "bg-gray-900 text-white hover:bg-gray-800",
        "disabled:opacity-50 disabled:cursor-not-allowed",
        className
      )}
    >
      {isExporting ? (
        <>
          <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
          Génération...
        </>
      ) : (
        <>
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          Exporter PDF
        </>
      )}
    </button>
  );
}

/**
 * Button for exporting all canvases from the main page
 */
interface ExportAllButtonProps {
  className?: string;
  /** Optional team ID override for admins viewing other teams */
  teamId?: string;
}

export function ExportAllButton({ className, teamId }: ExportAllButtonProps) {
  const [isExporting, setIsExporting] = useState(false);

  const handleExportAll = useCallback(async () => {
    setIsExporting(true);

    try {
      // Open the dedicated print page in a new window
      // Pass teamId if provided (for admin viewing other teams)
      const url = teamId ? `/print-all?teamId=${teamId}` : "/print-all";
      const printWindow = window.open(url, "_blank");
      if (!printWindow) {
        throw new Error("Impossible d'ouvrir la fenêtre d'impression. Vérifiez que les pop-ups ne sont pas bloqués.");
      }
    } catch (error) {
      console.error("Export failed:", error);
      alert(
        error instanceof Error
          ? error.message
          : "L'export a échoué. Veuillez réessayer."
      );
    } finally {
      setIsExporting(false);
    }
  }, [teamId]);

  return (
    <button
      onClick={handleExportAll}
      disabled={isExporting}
      className={cn(
        "px-8 py-3 bg-black text-white text-[16px] font-normal hover:bg-gray-800 transition-colors tracking-[-0.31px]",
        "disabled:opacity-50 disabled:cursor-not-allowed",
        className
      )}
    >
      {isExporting ? "Génération en cours..." : "Imprimer tous les canevas"}
    </button>
  );
}
