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

import { Typography } from "@scandic-hotels/design-system/Typography"

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

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

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

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

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

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

  const isRewardNight = priceType === "points"

  const guaranteeable =
    !guaranteeInfo &&
    !isCancelled &&
    !dateHasPassed(checkInDate, checkInTime) &&
    !isRewardNight

  if (!guaranteeable) {
    return null
  }

  function trackGuaranteeLateArrival() {
    trackMyStayPageLink("guarantee late arrival")
  }

  const arriveLateMsg = intl.formatMessage({
    defaultMessage:
      "Planning to arrive after 18.00? Secure your room by guaranteeing it with a credit card. Without the guarantee and in case of no-show, the room might be reallocated after 18:00.",
  })
  const text = intl.formatMessage({
    defaultMessage: "Guarantee late arrival",
  })

  return (
    <DialogTrigger>
      <Modal.Button icon="check" onClick={trackGuaranteeLateArrival}>
        {text}
      </Modal.Button>
      <Modal>
        <Dialog className={styles.dialog}>
          {({ close }) => (
            <Modal.Content>
              <Modal.Content.Header handleClose={close} title={text}>
                <Typography variant="Body/Paragraph/mdRegular">
                  <p>{arriveLateMsg}</p>
                </Typography>
              </Modal.Content.Header>
              <Modal.Content.Body>
                <Form />
              </Modal.Content.Body>
              <Modal.Content.Footer>
                <Modal.Content.Footer.Secondary onClick={close}>
                  {intl.formatMessage({ defaultMessage: "Back" })}
                </Modal.Content.Footer.Secondary>
                <Modal.Content.Footer.Primary form="guarantee" type="submit">
                  {intl.formatMessage({ defaultMessage: "Guarantee" })}
                </Modal.Content.Footer.Primary>
              </Modal.Content.Footer>
            </Modal.Content>
          )}
        </Dialog>
      </Modal>
    </DialogTrigger>
  )
}
