"use client"

import { useEffect, useState } from "react"

import useLang from "@/hooks/useLang"

import MeetingPackageWidgetSkeleton from "./Skeleton"

import styles from "./meetingPackageWidget.module.css"

const SOURCE =
  "https://scandic-bookingengine.s3.eu-central-1.amazonaws.com/script_stage.js"

interface MeetingPackageWidgetProps {
  destination?: string
  className?: string
}

export default function MeetingPackageWidget({
  destination,
  className,
}: MeetingPackageWidgetProps) {
  const lang = useLang()
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const script = document.createElement("script")
    script.src = SOURCE
    script.setAttribute("langcode", lang)
    script.setAttribute("whitelabel_id", "224905")
    script.setAttribute("widget_id", "scandic_default_new")
    script.setAttribute("version", "frontpage-scandic")
    if (destination) {
      script.setAttribute("destination", destination)
    }
    document.body.appendChild(script)

    function onLoad() {
      setIsLoading(false)
    }

    script.addEventListener("load", onLoad)

    return () => {
      script.removeEventListener("load", onLoad)
      document.body.removeChild(script)
    }
  }, [destination, lang])

  return (
    <div className={className}>
      {isLoading && <MeetingPackageWidgetSkeleton />}
      <div
        id="mp-booking-engine-iframe-container"
        className={`${styles.widget} ${isLoading ? styles.isLoading : ""}`}
      />
    </div>
  )
}
