"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 RoomSelectionPanel from "./RoomSelectionPanel"

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

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.allRooms,
  }))

  useEffect(() => {
    const pricesWithCurrencies = visibleRooms.flatMap((room) =>
      room.products
        .filter((product) => product.member || product.public)
        .map((product) => ({
          currency: (product.public?.localPrice.currency ||
            product.member?.localPrice.currency)!,
          price: (product.public?.localPrice.pricePerNight ||
            product.member?.localPrice.pricePerNight)!,
        }))
    )
    const lowestPrice = pricesWithCurrencies.reduce(
      (minPrice, { price }) => Math.min(minPrice, price),
      Infinity
    )

    const currency = pricesWithCurrencies[0]?.currency

    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}>
            <RoomSelectionPanel />
          </MultiRoomWrapper>
        </RoomProvider>
      ))}
    </div>
  )
}
