"use client"
import { useRouter, useSearchParams } from "next/navigation"
import { useCallback, useEffect, useMemo, useRef } from "react"

import { debounce } from "@/utils/debounce"

import RateSummary from "./RateSummary"
import RoomCard from "./RoomCard"
import {
  getHotelReservationQueryParams,
  rateCardEqualHeightSelector,
} from "./utils"

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

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

export default function RoomSelection({
  roomsAvailability,
  roomCategories,
  user,
  availablePackages,
  selectedPackages,
  setRateCode,
  rateSummary,
  hotelType,
}: RoomSelectionProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const isUserLoggedIn = !!user
  const roomRefs = useRef<HTMLLIElement[]>([])
  const { roomConfigurations, rateDefinitions } = roomsAvailability

  const equalizePriceOptionHeights = useCallback(() => {
    if (!roomRefs.current.length) return

    roomRefs.current.forEach((room) => {
      const options = room.querySelectorAll<HTMLDivElement>(
        `.${rateCardEqualHeightSelector}`
      )
      options.forEach((option) => {
        option.style.height = "auto"
      })
    })

    const numOptions =
      roomRefs.current[0]?.querySelectorAll<HTMLDivElement>(
        `.${rateCardEqualHeightSelector}`
      ).length || 0

    for (let i = 0; i < numOptions; i++) {
      let maxHeight = 0

      roomRefs.current.forEach((room) => {
        const option = room.querySelectorAll<HTMLDivElement>(
          `.${rateCardEqualHeightSelector}`
        )[i]
        if (option) {
          maxHeight = Math.max(maxHeight, option.offsetHeight)
        }
      })

      roomRefs.current.forEach((room) => {
        const option = room.querySelectorAll<HTMLDivElement>(
          `.${rateCardEqualHeightSelector}`
        )[i]
        if (option) {
          option.style.height = `${maxHeight}px`
        }
      })
    }
  }, [])

  useEffect(() => {
    const debouncedResizeHandler = debounce(function () {
      equalizePriceOptionHeights()
    })

    const observer = new ResizeObserver(debouncedResizeHandler)

    observer.observe(document.documentElement)

    return () => {
      if (observer) {
        observer.unobserve(document.documentElement)
      }
    }
  }, [roomRefs, equalizePriceOptionHeights])

  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
        )
      }
      if (selectedPackages.length > 0) {
        params.set(`room[${index}].packages`, selectedPackages.join(","))
      }
    })

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

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    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) => (
            <li
              key={roomConfiguration.roomTypeCode}
              ref={(el) => {
                if (el) roomRefs.current[index] = el
              }}
            >
              <RoomCard
                hotelId={roomsAvailability.hotelId.toString()}
                hotelType={hotelType}
                rateDefinitions={rateDefinitions}
                roomConfiguration={roomConfiguration}
                roomCategories={roomCategories}
                handleSelectRate={setRateCode}
                selectedPackages={selectedPackages}
                packages={availablePackages}
              />
            </li>
          ))}
        </ul>
        {rateSummary && (
          <RateSummary
            rateSummary={rateSummary}
            isUserLoggedIn={isUserLoggedIn}
            packages={availablePackages}
            roomsAvailability={roomsAvailability}
          />
        )}
      </form>
    </div>
  )
}
