import { Button } from "@/shared/common/ui/button";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { prepareForHtml2Canvas } from "@/shared/utils/chartExportUtils";
import { FileDown, Printer } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";

interface ExportButtonProps {
  dashboardRef:
    | React.RefObject<HTMLDivElement>
    | { current: HTMLDivElement | null };
}

export function ExportButton({ dashboardRef }: ExportButtonProps) {
  const [isExporting, setIsExporting] = useState(false);
  const { t } = useTranslation();
const exportToPdf = async () => {
    try {
      if (!dashboardRef.current) return;

      const originalNode = dashboardRef.current;
      const dashboardClone = originalNode.cloneNode(true) as HTMLElement;

      // Add marker classes to elements that need color preservation
      const elementsToPreserve = [
        ...dashboardClone.querySelectorAll(
          ".chart-container, .chart-legend, .status-indicator, .color-preserve, .logo-container",
        ),
      ];
      elementsToPreserve.forEach((el) => {
        el.classList.add("keep-color");
      });

      // Inject print-mode CSS into the clone
      const styleTag = document.createElement("style");
      styleTag.textContent = `
        * { color: #000 !important; background-color: #fff !important; border-color: #000 !important; }
        .keep-color { color: unset !important; background-color: unset !important; border-color: unset !important; }
        .keep-color * { color: unset !important; background-color: unset !important; border-color: unset !important; fill: unset !important; stroke: unset !important; }
        .keep-color svg, .keep-color svg * { fill: unset !important; stroke: unset !important; }
        .keep-color img { filter: none !important; -webkit-filter: none !important; }
      `;
      dashboardClone.appendChild(styleTag);

      // Render off-screen
      dashboardClone.style.position = "absolute";
      dashboardClone.style.top = "-10000px";
      dashboardClone.style.left = "0";
      dashboardClone.style.zIndex = "10000";
      document.body.appendChild(dashboardClone);

      // Patch oklch CSS vars and inline SVG presentation attribute CSS variables
      // so html2canvas can render Recharts SVG fills correctly.
      const patch = prepareForHtml2Canvas(dashboardClone);

      let canvas;
      try {
        canvas = await html2canvas(dashboardClone, {
          useCORS: true,
          backgroundColor: "#ffffff",
          scale: 2,
          logging: false,
        });
      } finally {
        patch.restore();
        document.body.removeChild(dashboardClone);
      }

      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF({
        orientation: "portrait",
        unit: "px",
        format: [canvas.width, canvas.height],
      });
      pdf.addImage(imgData, "PNG", 0, 0, canvas.width, canvas.height);
      pdf.save("dashboard.pdf");
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  // Fallback method using direct printing
  const handlePrintFallback = () => {
    if (!dashboardRef.current) return;

    try {
      // Create a print-specific stylesheet
      const style = document.createElement("style");
      style.innerHTML = `
        @media print {
          body * {
            visibility: hidden;
          }
          #dashboard-print-container, #dashboard-print-container * {
            visibility: visible;
          }
          #dashboard-print-container {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
          }
          .chart-container {
            page-break-inside: avoid;
          }
        }
      `;
      document.head.appendChild(style);

      // Create print container
      const printContainer = document.createElement("div");
      printContainer.id = "dashboard-print-container";

      // Clone the dashboard content
      const clone = dashboardRef.current.cloneNode(true);
      printContainer.appendChild(clone);
      document.body.appendChild(printContainer);

      // Print
      window.print();

      // Clean up
      setTimeout(() => {
        if (printContainer.parentNode) {
          printContainer.parentNode.removeChild(printContainer);
        }
        document.head.removeChild(style);
      }, 500);
    } catch (error) {
      console.error("Error during print:", error);
      alert("There was an error with printing. Please try again.");
    }
  };

  const pdfLabel = isExporting
    ? t("dashboard.exporting")
    : t("dashboard.exportPdf");
  const printLabel = t("dashboard.print");

  return (
    <div className="flex items-center gap-2 max-w-full overflow-visible">
      {/* sm+ : full buttons with visible labels */}
      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="hidden sm:inline-flex items-center gap-1"
            onClick={exportToPdf}
            disabled={isExporting}>
            <FileDown className="h-4 w-4" />
            <span>{pdfLabel}</span>
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <span>{pdfLabel}</span>
        </TooltipContent>
      </Tooltip>

      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="hidden sm:inline-flex items-center gap-1"
            onClick={handlePrintFallback}
            disabled={isExporting}>
            <Printer className="h-4 w-4" />
            <span>{printLabel}</span>
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <span>{printLabel}</span>
        </TooltipContent>
      </Tooltip>

      {/* < sm : compact icon-only buttons with tooltip labels */}
      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="outline"
            size="icon"
            className="sm:hidden"
            onClick={exportToPdf}
            disabled={isExporting}
            aria-label={pdfLabel}>
            <FileDown className="h-4 w-4" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <span>{pdfLabel}</span>
        </TooltipContent>
      </Tooltip>

      <Tooltip>
        <TooltipTrigger asChild>
          <Button
            variant="outline"
            size="icon"
            className="sm:hidden"
            onClick={handlePrintFallback}
            disabled={isExporting}
            aria-label={printLabel}>
            <Printer className="h-4 w-4" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <span>{printLabel}</span>
        </TooltipContent>
      </Tooltip>
    </div>
  );
}
