"use client"
import { useRouter, useSearchParams } from "next/navigation"
import { useMemo } from "react"

import RateSummary from "./RateSummary"
import RoomCard from "./RoomCard"
import { getHotelReservationQueryParams } from "./utils"

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

import type { RoomSelectionProps } from "@/types/components/hotelReservation/selectRate/roomSelection"

export default function RoomSelection({
  roomsAvailability,
  roomCategories,
  user,
  packages,
  selectedPackages,
  setRateSummary,
  rateSummary,
}: RoomSelectionProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const isUserLoggedIn = !!user

  const { roomConfigurations, rateDefinitions } = roomsAvailability

  const queryParams = useMemo(() => {
    const params = new URLSearchParams(searchParams)
    const searchParamsObject = getHotelReservationQueryParams(searchParams)

    searchParamsObject.room.forEach((item, index) => {
      if (rateSummary?.roomTypeCode) {
        params.set(`room[${index}].roomtype`, rateSummary.roomTypeCode)
      }
      if (rateSummary?.public?.rateCode) {
        params.set(`room[${index}].ratecode`, rateSummary.public.rateCode)
      }
      if (rateSummary?.member?.rateCode) {
        params.set(
          `room[${index}].counterratecode`,
          rateSummary.member.rateCode
        )
      }
      if (selectedPackages.length > 0) {
        params.set(`room[${index}].packages`, selectedPackages.join(","))
      }
    })

    return params
  }, [searchParams, rateSummary, selectedPackages])

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    router.push(`select-bed?${queryParams}`)
  }

  return (
    <div className={styles.wrapper}>
      <form
        method="GET"
        action={`select-bed?${searchParams}`}
        onSubmit={handleSubmit}
      >
        <ul className={styles.roomList}>
          {roomConfigurations.map((roomConfiguration) => (
            <li key={roomConfiguration.roomTypeCode}>
              <RoomCard
                hotelId={roomsAvailability.hotelId.toString()}
                rateDefinitions={rateDefinitions}
                roomConfiguration={roomConfiguration}
                roomCategories={roomCategories}
                handleSelectRate={setRateSummary}
                selectedPackages={selectedPackages}
                packages={packages}
              />
            </li>
          ))}
        </ul>
        {rateSummary && (
          <RateSummary
            rateSummary={rateSummary}
            isUserLoggedIn={isUserLoggedIn}
            packages={packages}
            roomsAvailability={roomsAvailability}
          />
        )}
      </form>
    </div>
  )
}
