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

import RateSummary from "./RateSummary"
import RoomCard from "./RoomCard"

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({
  roomConfigurations,
  roomCategories,
  user,
}: RoomSelectionProps) {
  const [rateSummary, setRateSummary] = useState<Rate | null>(null)

  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(`select-bed?${queryParams}`)
  }

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