"use client"

import { useState } from "react"

import { RoomsAvailability } from "@/server/routers/hotels/output"

import RoomFilter from "../RoomFilter"
import RoomSelection from "../RoomSelection"

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

import { RoomProps } from "@/types/components/hotelReservation/selectRate/room"
import { RoomPackageCodes } from "@/types/components/hotelReservation/selectRate/roomFilter"

export default function Rooms({
  roomsAvailability,
  roomCategories = [],
  user,
  packages,
}: RoomProps) {
  const [rooms, setRooms] = useState<RoomsAvailability>(roomsAvailability)

  function handleFilter(filter: Record<string, boolean | undefined>) {
    const selectedCodes = Object.keys(filter).filter((key) => filter[key])

    if (selectedCodes.length === 0) {
      setRooms(roomsAvailability)
      return
    }

    const filteredRooms = roomsAvailability.roomConfigurations.filter((room) =>
      room.features.some((feature) =>
        selectedCodes.includes(feature.code as RoomPackageCodes)
      )
    )
    setRooms({ ...roomsAvailability, roomConfigurations: filteredRooms })
  }

  return (
    <div className={styles.content}>
      <RoomFilter
        numberOfRooms={rooms.roomConfigurations.length}
        onFilter={handleFilter}
        filterOptions={packages}
      />
      <RoomSelection
        roomsAvailability={rooms}
        roomCategories={roomCategories}
        user={user}
      />
    </div>
  )
}
