"use client"
import { usePathname, 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,
  availablePackages,
  selectedPackages,
  isUserLoggedIn,
  setRateCode,
  rateSummary,
  hotelType,
}: RoomSelectionProps) {
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  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
        )
      }
      selectedPackages.length > 0
        ? params.set(`room[${index}].packages`, selectedPackages.join(","))
        : params.delete(`room[${index}].packages`)
    })

    return params
  }, [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>
  )
}
