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

import { dt } from "@/lib/dt"
import { trpc } from "@/lib/trpc/client"
import { useMyStayStore } from "@/stores/my-stay"

import Modal from "@/components/HotelReservation/MyStay/Modal"
import PriceContainer from "@/components/HotelReservation/MyStay/ReferenceCard/PriceContainer"
import Divider from "@/components/TempDesignSystem/Divider"
import { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"

import PriceAndDate from "./PriceAndDate"

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

import type { Lang } from "@/constants/languages"

interface ConfirmationProps {
  checkInDate: string
  checkOutDate: string
  closeModal: () => void
  newPrice: string
}

function formatDate(date: Date | string, lang: Lang) {
  return dt(date).locale(lang).format("dddd, DD MMM, YYYY")
}

export default function Confirmation({
  checkInDate,
  checkOutDate,
  closeModal,
  newPrice,
}: ConfirmationProps) {
  const intl = useIntl()
  const lang = useLang()
  const utils = trpc.useUtils()
  const { bookedRoom, oldPrice, totalAdults, totalChildren } = useMyStayStore(
    (state) => ({
      bookedRoom: state.bookedRoom,
      oldPrice: state.totalPrice,
      totalAdults: state.rooms.reduce(
        (total, room) => total + (room.isCancelled ? 0 : room.adults),
        0
      ),
      totalChildren: state.rooms.reduce(
        (total, room) =>
          total + (room.isCancelled ? 0 : room.childrenInRoom.length),
        0
      ),
    })
  )

  const updateBooking = trpc.booking.update.useMutation({
    onSuccess: (updatedBooking) => {
      if (updatedBooking) {
        utils.booking.get.invalidate({
          refId: updatedBooking.refId,
        })

        toast.success(
          intl.formatMessage({
            defaultMessage: "Your stay was updated",
          })
        )

        closeModal()
      } else {
        toast.error(
          intl.formatMessage({
            defaultMessage: "Failed to update your stay",
          })
        )
      }
    },
    onError: () => {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Failed to update your stay",
        })
      )
    },
  })

  function handleModifyStay() {
    updateBooking.mutate({
      refId: bookedRoom.refId,
      checkInDate,
      checkOutDate,
      language: lang,
    })
  }

  const originalCheckIn = formatDate(bookedRoom.checkInDate, lang)
  const originalCheckOut = formatDate(bookedRoom.checkOutDate, lang)
  const newCheckIn = formatDate(checkInDate, lang)
  const newCheckOut = formatDate(checkOutDate, lang)

  const nights = dt(newCheckOut)
    .startOf("day")
    .diff(dt(newCheckIn).startOf("day"), "days")

  const nightsText = intl.formatMessage(
    {
      defaultMessage: "{totalNights, plural, one {# night} other {# nights}}",
    },
    { totalNights: nights }
  )
  const newDatesLabel = intl.formatMessage({
    defaultMessage: "New dates",
  })
  const oldDatesLabel = intl.formatMessage({
    defaultMessage: "Old dates",
  })
  const title = intl.formatMessage({
    defaultMessage: "Confirm date change",
  })
  const totalDueMsg = intl.formatMessage({
    defaultMessage: "Pay at the hotel",
  })
  const adultsText = intl.formatMessage(
    {
      defaultMessage: "{totalAdults, plural, one {# adult} other {# adults}}",
    },
    { totalAdults: totalAdults }
  )
  const childrenText = intl.formatMessage(
    {
      defaultMessage:
        "{totalChildren, plural, one {# child} other {# children}}",
    },
    { totalChildren: totalChildren }
  )

  return (
    <Modal.Content>
      <Modal.Content.Header handleClose={closeModal} title={title} />
      <Modal.Content.Body>
        <div className={styles.container}>
          <div className={styles.dateComparison}>
            <PriceAndDate
              checkInDate={originalCheckIn}
              checkOutDate={originalCheckOut}
              label={oldDatesLabel}
              price={oldPrice}
              striked
            />

            <Divider color="primaryLightSubtle" />

            <PriceAndDate
              checkInDate={newCheckIn}
              checkOutDate={newCheckOut}
              label={newDatesLabel}
              price={newPrice}
            />
          </div>

          <PriceContainer
            adultsText={adultsText}
            childrenText={childrenText}
            nightsText={nightsText}
            price={newPrice}
            text={totalDueMsg}
            totalChildren={totalChildren}
          />
        </div>
      </Modal.Content.Body>
      <Modal.Content.Footer>
        <Modal.Content.Footer.Secondary onClick={closeModal}>
          {intl.formatMessage({ defaultMessage: "Back" })}
        </Modal.Content.Footer.Secondary>
        <Modal.Content.Footer.Primary
          disabled={updateBooking.isPending}
          onClick={handleModifyStay}
        >
          {intl.formatMessage({ defaultMessage: "Confirm" })}
        </Modal.Content.Footer.Primary>
      </Modal.Content.Footer>
    </Modal.Content>
  )
}
