"use client"
import { createEvent } from "ics"
import { useIntl } from "react-intl"

import { dt } from "@scandic-hotels/common/dt"
import { logger } from "@scandic-hotels/common/logger"
import { toast } from "@scandic-hotels/design-system/Toast"

import useLang from "@/hooks/useLang"

import type { AddToCalendarProps } from "@/types/components/hotelReservation/bookingConfirmation/actions/addToCalendar"

export default function AddToCalendar({
  checkInDate,
  event,
  hotelName,
  renderButton,
}: AddToCalendarProps) {
  const lang = useLang()
  const intl = useIntl()

  async function downloadBooking() {
    try {
      const d = dt(checkInDate).locale(lang).format("YYYY-MM-DD")
      const filename = `${hotelName.toLowerCase().split(" ").join("_")}-${d}.ics`

      createEvent(event, (error, value) => {
        if (error) {
          logger.error("ICS Error:", error)
          toast.error(
            intl.formatMessage({
              defaultMessage: "Failed to add to calendar",
            })
          )
          return
        }

        const file = new File([value], filename, { type: "text/calendar" })
        const url = URL.createObjectURL(file)
        const anchor = document.createElement("a")
        anchor.href = url
        anchor.download = filename
        document.body.appendChild(anchor)
        anchor.click()
        document.body.removeChild(anchor)
        URL.revokeObjectURL(url)
      })
    } catch (error) {
      logger.error("Download error:", error)
      toast.error(
        intl.formatMessage({
          defaultMessage: "Failed to add to calendar",
        })
      )
    }
  }

  return renderButton(downloadBooking)
}
