"use client"
import { Dialog, DialogTrigger } from "react-aria-components"
import { useIntl } from "react-intl"

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

import Modal from "@/components/HotelReservation/MyStay/Modal"
import { trackMyStayPageLink } from "@/utils/tracking"

import { dateHasPassed } from "../utils"
import Alerts from "./Alerts"
import Steps from "./Steps"

export default function ChangeDates() {
  const intl = useIntl()

  const { canChangeDate, checkInDate, checkInTime, isCancelled, priceType } =
    useMyStayStore((state) => ({
      canChangeDate: state.bookedRoom.canChangeDate,
      checkInDate: state.bookedRoom.checkInDate,
      checkInTime: state.hotel.hotelFacts.checkin.checkInTime,
      isCancelled: state.bookedRoom.isCancelled,
      priceType: state.bookedRoom.priceType,
    }))

  const isRewardNight = priceType === "points"
  const isDisabled =
    canChangeDate &&
    !isCancelled &&
    !isRewardNight &&
    dateHasPassed(checkInDate, checkInTime)

  function trackChangeDates() {
    trackMyStayPageLink("modify dates")
  }

  const text = intl.formatMessage({ defaultMessage: "Change dates" })
  return (
    <DialogTrigger>
      <Modal.Button
        icon="edit_calendar"
        isDisabled={isDisabled}
        onClick={trackChangeDates}
      >
        {text}
      </Modal.Button>
      <Modal>
        <Dialog>
          {({ close }) => (
            <Alerts closeModal={close}>
              <Steps closeModal={close} />
            </Alerts>
          )}
        </Dialog>
      </Modal>
    </DialogTrigger>
  )
}
