"use client"
import { useEffect } from "react"

import { useRatesStore } from "@/stores/select-rate"

import RoomProvider from "@/providers/SelectRate/RoomProvider"
import { trackLowestRoomPrice } from "@/utils/tracking"

import MultiRoomWrapper from "./MultiRoomWrapper"
import NoAvailabilityAlert from "./NoAvailabilityAlert"
import RoomsHeader from "./RoomsHeader"
import RoomsList from "./RoomsList"

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

import type { PriceProduct } from "@/types/trpc/routers/hotel/roomAvailability"

export default function Rooms() {
  const {
    arrivalDate,
    bookingRooms,
    departureDate,
    hotelId,
    rooms,
    visibleRooms,
  } = useRatesStore((state) => ({
    arrivalDate: state.booking.fromDate,
    bookingRooms: state.booking.rooms,
    departureDate: state.booking.toDate,
    hotelId: state.booking.hotelId,
    rooms: state.rooms,
    visibleRooms: state.roomConfigurations,
  }))

  useEffect(() => {
    const pricesWithCurrencies = visibleRooms.flatMap((roomConfiguration) =>
      roomConfiguration.flatMap((room) =>
        room.products
          .filter(
            (product): product is PriceProduct =>
              !!(
                ("public" in product && product.public) ||
                ("member" in product && product.member)
              )
          )
          .map((product) => ({
            currency: (product.public?.localPrice.currency ||
              product.member?.localPrice.currency)!,
            price: (product.public?.localPrice.pricePerNight ||
              product.member?.localPrice.pricePerNight)!,
          }))
      )
    )

    // Specific n/a when no prices available in reward night and voucher scenarios
    const lowestPrice = pricesWithCurrencies.length
      ? pricesWithCurrencies
          .reduce((minPrice, { price }) => Math.min(minPrice, price), Infinity)
          .toString()
      : "n/a"

    const currency = pricesWithCurrencies.length
      ? pricesWithCurrencies[0]?.currency
      : "n/a"

    trackLowestRoomPrice({
      hotelId,
      arrivalDate,
      departureDate,
      lowestPrice: lowestPrice,
      currency: currency,
    })
  }, [arrivalDate, departureDate, hotelId, visibleRooms])

  return (
    <div className={styles.content}>
      {bookingRooms.map((room, idx) => (
        <RoomProvider
          key={`${room.rateCode}-${room.roomTypeCode}-${idx}`}
          idx={idx}
          room={rooms[idx]}
        >
          <MultiRoomWrapper isMultiRoom={bookingRooms.length > 1}>
            <RoomsHeader />
            <NoAvailabilityAlert />
            <RoomsList />
          </MultiRoomWrapper>
        </RoomProvider>
      ))}
    </div>
  )
}
