"use client"

import { useCallback, 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 type { RoomSelectionProps } from "@/types/components/hotelReservation/selectRate/roomSelection"

export default function Rooms({
  roomsAvailability,
  roomCategories = [],
  user,
  packages,
}: RoomSelectionProps) {
  const defaultRooms = roomsAvailability.roomConfigurations.filter(
    (room) => room.features.length === 0
  )
  const [rooms, setRooms] = useState<RoomsAvailability>({
    ...roomsAvailability,
    roomConfigurations: defaultRooms,
  })

  console.log(rooms)

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

      if (selectedCodes.length === 0) {
        setRooms({
          ...roomsAvailability,
          roomConfigurations: defaultRooms,
        })
        return
      }

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

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