import React, { useEffect } from "react"
import html2canvas from "html2canvas"

import useStore from "../utils/store"
import { uploadImageToBucket } from "../utils/lib"
import { slugify } from "../utils/creatorUtils"
import { eventBus } from "../utils/eventBus"
// import { SVGS } from "../assets/svgs"

function proxify(link: string) {
  // Validar que el enlace no sea vacío
  if (!link) {
    return "https://placehold.co/100x100"
  }

  const encodedUrl = btoa(link)

  return `http://localhost:3000/proxy?url=${encodedUrl}`
}

const PreviewGenerator: React.FC = () => {
  const history = useStore((state) => state.history)
  const auth = useStore((state) => state.auth)

  const syllabus = history[history.length - 1]

  useEffect(() => {
    const handleDownload = () => {
      eventBus.emit("course-generation", {
        message: "📷 Generating preview image...",
      })
      const previewElement = document.getElementById("preview")
      if (previewElement) {
        html2canvas(previewElement, {
          useCORS: true,
        }).then(async (canvas) => {
          // const anchor = document.createElement("a")
          // anchor.href = canvas.toDataURL("image/png")
          // anchor.download = "preview.png"
          // anchor.click()

          const imageUrl = canvas.toDataURL("image/png")

          await uploadImageToBucket(
            imageUrl,
            `courses/${slugify(syllabus.courseInfo?.title || "")}/preview.png`
          )
          eventBus.emit("course-generation", {
            message: "✅ Preview image generated and uploaded to course.",
          })
        })
      }
    }
    handleDownload()
  }, [])

  return (
    <div className="fixed bg-white z-50 border-2 border-gray-200 ">
      <div
        id="preview"
        style={{
          width: "1200px",
          height: "630px",
          background: "white",
        }}
      >
        <div className="bg-learnpack-blue p-10 rounded-md" />
        <div className="px-20 -mt-5">
          <h1 className="text-7xl font-bold mt-14">
            {syllabus.courseInfo?.title}
          </h1>
          {/* <p className="mt-5 text-sm">{syllabus.courseInfo?.description}</p> */}
          <div className="flex items-center gap-2 mt-10">
            <img
              src={proxify(auth.user?.profile?.avatar_url || "")}
              alt="Profile"
              className="w-10 h-10 rounded-full mt-3"
            />
            <div>
              <p className=" text-sm font-bold ">
                Author: {auth.user?.first_name} {auth.user?.last_name}
              </p>
              <small className=" text-sm">
                Published on: {new Date().toLocaleDateString()}
              </small>
            </div>
            <div className="ml-auto">
              <img src="logo.png" className="w-10 h-10" />
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default PreviewGenerator
