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

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

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

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

export default function RoomSelection({
  roomsAvailability,
  roomCategories,
  user,
}: RoomSelectionProps) {
  const [rateSummary, setRateSummary] = useState<Rate | null>(null)

  const router = useRouter()
  const searchParams = useSearchParams()
  const isUserLoggedIn = !!user

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const searchParamsObject = getHotelReservationQueryParams(searchParams)

    const queryParams = new URLSearchParams(searchParams)

    searchParamsObject.room.forEach((item, index) => {
      if (rateSummary?.roomTypeCode) {
        queryParams.set(`room[${index}].roomtype`, rateSummary.roomTypeCode)
      }
      if (rateSummary?.public?.rateCode) {
        queryParams.set(`room[${index}].ratecode`, rateSummary.public.rateCode)
      }
      if (rateSummary?.member?.rateCode) {
        queryParams.set(
          `room[${index}].counterratecode`,
          rateSummary.member.rateCode
        )
      }
    })

    router.push(`select-bed?${queryParams}`)
  }

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