"use client"

import { useMyStayStore } from "@/stores/my-stay"

import AddToCalendar from "@/components/HotelReservation/AddToCalendar"
import { generateDateTime } from "@/components/HotelReservation/BookingConfirmation/Header/Actions/helpers"

import { dateHasPassed } from "../utils"
import AddToCalendarButton from "./AddToCalendarButton"

import type { EventAttributes } from "ics"

export default function AddToCalendarAction() {
  const { checkInDate, checkOutDate, createDateTime, hotel } = useMyStayStore(
    (state) => ({
      checkInDate: state.bookedRoom.checkInDate,
      checkOutDate: state.bookedRoom.checkOutDate,
      createDateTime: state.bookedRoom.createDateTime,
      hotel: state.hotel,
    })
  )

  const calendarEvent: EventAttributes = {
    busyStatus: "FREE",
    categories: ["booking", "hotel", "stay"],
    created: generateDateTime(createDateTime),
    description: hotel.hotelContent.texts.descriptions?.medium,
    end: generateDateTime(checkOutDate),
    endInputType: "utc",
    geo: {
      lat: hotel.location.latitude,
      lon: hotel.location.longitude,
    },
    location: `${hotel.address.streetAddress}, ${hotel.address.zipCode} ${hotel.address.city} ${hotel.address.country}`,
    start: generateDateTime(checkInDate),
    startInputType: "utc",
    status: "CONFIRMED",
    title: hotel.name,
    url: hotel.contactInformation.websiteUrl,
  }

  const disabled = dateHasPassed(
    checkInDate,
    hotel.hotelFacts.checkin.checkInTime
  )

  return (
    <AddToCalendar
      checkInDate={checkInDate}
      event={calendarEvent}
      hotelName={hotel.name}
      renderButton={(onPress) => (
        <AddToCalendarButton disabled={disabled} onPress={onPress} />
      )}
    />
  )
}
