"use client"
import { useWatch } from "react-hook-form"
import { useIntl } from "react-intl"

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

import PriceContainer from "@/components/HotelReservation/MyStay/ReferenceCard/PriceContainer"
import { formatPrice } from "@/utils/numberFormatting"

import type { CancelStayFormValues } from "@/types/components/hotelReservation/myStay/cancelStay"

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

  const { bookedRoom, nights, rooms } = useMyStayStore((state) => ({
    bookedRoom: state.bookedRoom,
    nights: dt(state.bookedRoom.checkOutDate)
      .startOf("day")
      .diff(dt(state.bookedRoom.checkInDate).startOf("day"), "days"),
    rooms: state.rooms,
  }))
  const formRooms = useWatch<CancelStayFormValues>({ name: "rooms" })

  if (!Array.isArray(formRooms)) {
    return null
  }

  const { totalAdults, totalChildren } = formRooms.reduce(
    (total, formRoom) => {
      if (formRoom.checked) {
        const room = rooms.find((r) => r.refId === formRoom.refId)
        if (room) {
          total.totalAdults = total.totalAdults + room.adults
          if (room.childrenInRoom.length) {
            total.totalChildren =
              total.totalChildren + room.childrenInRoom.length
          }
        }
      }
      return total
    },
    { totalAdults: 0, totalChildren: 0 }
  )

  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 }
  )
  const nightsText = intl.formatMessage(
    {
      defaultMessage: "{totalNights, plural, one {# night} other {# nights}}",
    },
    { totalNights: nights }
  )

  return (
    <PriceContainer
      adultsText={adultsText}
      childrenText={childrenText}
      nightsText={nightsText}
      price={formatPrice(intl, 0, bookedRoom.currencyCode)}
      text={intl.formatMessage({ defaultMessage: "Total due" })}
      totalChildren={totalChildren}
    />
  )
}
