"use client"

import { useCallback, useState } from "react"

import RoomFilter from "../RoomFilter"
import RoomSelection from "../RoomSelection"
import { getLowestPricedDuplicateRooms } from "./utils"

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

import {
  RoomPackageCodeEnum,
  type RoomPackageCodes,
} from "@/types/components/hotelReservation/selectRate/roomFilter"
import type { RoomSelectionProps } from "@/types/components/hotelReservation/selectRate/roomSelection"
import type {
  RoomConfiguration,
  RoomsAvailability,
} from "@/server/routers/hotels/output"

export default function Rooms({
  roomsAvailability,
  roomCategories = [],
  user,
  packages,
}: Omit<RoomSelectionProps, "selectedPackages">) {
  const visibleRooms: RoomConfiguration[] = getLowestPricedDuplicateRooms(
    roomsAvailability.roomConfigurations
  )

  const [rooms, setRooms] = useState<RoomsAvailability>({
    ...roomsAvailability,
    roomConfigurations: visibleRooms,
  })
  const [selectedPackages, setSelectedPackages] = useState<RoomPackageCodes[]>(
    []
  )

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

      setSelectedPackages(filteredPackages)

      if (filteredPackages.length === 0) {
        setRooms({
          ...roomsAvailability,
          roomConfigurations: visibleRooms,
        })
        return
      }

      const filteredRooms = visibleRooms.filter((room) =>
        filteredPackages.every((filteredPackage) =>
          room.features.some((feature) => feature.code === filteredPackage)
        )
      )
      setRooms({ ...roomsAvailability, roomConfigurations: filteredRooms })
    },
    [roomsAvailability, visibleRooms]
  )

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