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

import { dt } from "@/lib/dt"

import { toast } from "@/components/TempDesignSystem/Toasts"
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) {
          console.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) {
      console.error("Download error:", error)
      toast.error(
        intl.formatMessage({
          defaultMessage: "Failed to add to calendar",
        })
      )
    }
  }

  return renderButton(downloadBooking)
}
