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

import { convertObjToSearchParams } from "@/utils/url"

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

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

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

export default function RoomSelection({
  roomsAvailability,
  roomCategories,
  availablePackages,
  selectedPackages,
  isUserLoggedIn,
  setRateCode,
  rateSummary,
  hotelType,
}: RoomSelectionProps) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const { roomConfigurations, rateDefinitions } = roomsAvailability

  const queryParams = useMemo(() => {
    // TODO: handle multiple rooms
    const newSearchParams = convertObjToSearchParams(
      {
        rooms: [
          {
            roomTypeCode: rateSummary?.roomTypeCode,
            rateCode: rateSummary?.public.rateCode,
            counterRateCode: rateSummary?.member?.rateCode,
            packages: selectedPackages,
          },
        ],
      },
      searchParams
    )

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

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()

    window.history.replaceState(
      null,
      "",
      `${pathname}?${queryParams.toString()}`
    )
    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, index) => (
            <RoomCard
              hotelId={roomsAvailability.hotelId.toString()}
              hotelType={hotelType}
              rateDefinitions={rateDefinitions}
              roomConfiguration={roomConfiguration}
              roomCategories={roomCategories}
              handleSelectRate={setRateCode}
              selectedPackages={selectedPackages}
              packages={availablePackages}
              key={roomConfiguration.roomTypeCode}
            />
          ))}
        </ul>
        {rateSummary && (
          <RateSummary
            rateSummary={rateSummary}
            isUserLoggedIn={isUserLoggedIn}
            packages={availablePackages}
            roomsAvailability={roomsAvailability}
          />
        )}
      </form>
    </div>
  )
}
