"use client";
import { useRef, useState } from "react";
import * as htmlToImage from "html-to-image";
import OrderVisionBoard from "./orderVisionBoard";

interface VisionBoardDownloaderProps {
  vision_board_summary: any;
  order_id: string;
}

export default function VisionBoardDownloader({
  vision_board_summary,
  order_id,
}: VisionBoardDownloaderProps) {
  const boardRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(false);
  const [reloadKey, setReloadKey] = useState(0);

  const waitForImagesToLoad = (node: HTMLElement): Promise<void> => {
    const images = Array.from(node.querySelectorAll("img"));
    if (images.length === 0) return Promise.resolve();

    return new Promise((resolve) => {
      let loaded = 0;
      images.forEach((img) => {
        if (img.complete) {
          loaded++;
          if (loaded === images.length) resolve();
        } else {
          img.onload = img.onerror = () => {
            loaded++;
            if (loaded === images.length) resolve();
          };
        }
      });
    });
  };

  const handleDownload = async () => {
    setLoading(true);

    try {
      setReloadKey((prev) => prev + 1);

      // Give React time to render
      await new Promise((res) => setTimeout(res, 300));

      if (!boardRef.current) return;

      await waitForImagesToLoad(boardRef.current);

      const node = boardRef.current;
      const rect = node.getBoundingClientRect();

      const exportWidth = 1080;
      const exportHeight = (exportWidth * 16) / 9;

      const scale = Math.max(exportWidth / rect.width, exportHeight / rect.height);

      const dataUrl = await htmlToImage.toPng(node, {
        pixelRatio: 2,
        backgroundColor: "#ffffff",
        cacheBust: true,
        width: rect.width * scale,
        height: rect.height * scale,
        style: {
          transform: `scale(${scale})`,
          transformOrigin: "top left",
          width: `${rect.width}px`,
          height: `${rect.height}px`,
          margin: "0",
          padding: "0",
        },
      });

      const img = new Image();
      img.src = dataUrl;
      await new Promise((resolve) => (img.onload = resolve));

      const canvas = document.createElement("canvas");
      canvas.width = exportWidth;
      canvas.height = exportHeight;
      const ctx = canvas.getContext("2d");
      if (!ctx) throw new Error("Canvas context not available");

      const scaleToFit = Math.max(exportWidth / img.width, exportHeight / img.height);
      const newWidth = img.width * scaleToFit;
      const newHeight = img.height * scaleToFit;
      const offsetX = (exportWidth - newWidth) / 2;
      const offsetY = (exportHeight - newHeight) / 2;

      ctx.drawImage(img, offsetX, offsetY, newWidth, newHeight);
      const finalUrl = canvas.toDataURL("image/png");

      const link = document.createElement("a");
      link.download = `morni-vision-board-${order_id}.png`;
      link.href = finalUrl;
      link.click();
    } catch (error) {
      console.error("Download failed:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="relative flex flex-col items-center">
      {/* Vision board preview */}
      <div
        ref={boardRef}
        key={reloadKey}
        className="w-full bg-white aspect-[9/16] overflow-hidden flex items-center justify-center"
      >
        <OrderVisionBoard vision_board_summary={vision_board_summary} />
      </div>

      {/* Loading overlay */}
      {loading && (
        <div className="absolute inset-0 z-50 flex flex-col items-center justify-center bg-white/80 backdrop-blur-sm">
          <svg
            className="h-8 w-8 animate-spin text-gray-700 mb-2"
            xmlns="http://www.w3.org/2000/svg"
            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-8v4a4 4 0 00-4 4H4z"
            />
          </svg>
          <p className="text-sm text-gray-800">Preparing your board...</p>
        </div>
      )}

      {/* Download button */}
      <div className="mt-4">
        <button
          onClick={handleDownload}
          className="btn-outline flex items-center justify-center gap-2 border border-gray-700 px-4 py-2 disabled:opacity-60"
          disabled={loading}
        >
          {loading ? "Downloading..." : "Download Visionboard"}
        </button>
      </div>
    </div>
  );
}
