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

import RoomCard from "./RoomCard"

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

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

export default function RoomSelection({
  alternatives,
  nextPath,
  nrOfNights,
  nrOfAdults,
}: RoomSelectionProps) {
  const router = useRouter()
  const searchParams = useSearchParams()

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const queryParams = new URLSearchParams(searchParams)
    queryParams.set("roomClass", e.currentTarget.roomClass?.value)
    queryParams.set("flexibility", e.currentTarget.flexibility?.value)
    router.push(`${nextPath}?${queryParams}`)
  }

  return (
    <div className={styles.wrapper}>
      <ul className={styles.roomList}>
        {alternatives.map((room) => (
          <li key={room.id}>
            <form
              method="GET"
              action={`${nextPath}?${searchParams}`}
              onSubmit={handleSubmit}
            >
              <input
                type="hidden"
                name="roomClass"
                value={room.id}
                id={`room-${room.id}`}
              />
              <RoomCard
                room={room}
                nrOfAdults={nrOfAdults}
                nrOfNights={nrOfNights}
                breakfastIncluded={room.breakfastIncluded}
              />
            </form>
          </li>
        ))}
      </ul>
    </div>
  )
}
