import { ChildBedTypeEnum } from "@/constants/booking"

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

import { ChildBedMapEnum } from "@/types/components/bookingWidget/enums"
import { BookingData } from "@/types/components/hotelReservation/enterDetails/bookingData"
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
import type {
  Child,
  SelectRateSearchParams,
} from "@/types/components/hotelReservation/selectRate/selectRate"

export function getHotelReservationQueryParams(searchParams: URLSearchParams) {
  return getFormattedUrlQueryParams(searchParams, {
    adults: "number",
    age: "number",
    bed: ChildBedMapEnum,
  }) as SelectRateSearchParams
}

export const bedTypeMap: Record<number, ChildBedTypeEnum> = {
  [ChildBedMapEnum.IN_ADULTS_BED]: ChildBedTypeEnum.ParentsBed,
  [ChildBedMapEnum.IN_CRIB]: ChildBedTypeEnum.Crib,
  [ChildBedMapEnum.IN_EXTRA_BED]: ChildBedTypeEnum.ExtraBed,
}

export function generateChildrenString(children: Child[]): string {
  return `[${children
    .map((child) => {
      const age = child.age
      const bedType = bedTypeMap[parseInt(child.bed.toString())]
      return `${age}:${bedType}`
    })
    .join(",")}]`
}

export function getQueryParamsForEnterDetails(
  searchParams: URLSearchParams
): BookingData {
  const selectRoomParamsObject = getHotelReservationQueryParams(searchParams)

  const { room } = selectRoomParamsObject
  return {
    fromDate: selectRoomParamsObject.fromDate,
    toDate: selectRoomParamsObject.toDate,
    hotel: selectRoomParamsObject.hotel,
    rooms: room.map((room) => ({
      adults: room.adults, // TODO: Handle multiple rooms
      children: room.child, // TODO: Handle multiple rooms and children
      roomTypeCode: room.roomtype,
      rateCode: room.ratecode,
      packages: room.packages?.split(",") as RoomPackageCodeEnum[],
    })),
  }
}

export function createSelectRateUrl(roomData: BookingData) {
  const { hotel, fromDate, toDate } = roomData
  const params = new URLSearchParams({ fromDate, toDate, hotel })

  roomData.rooms.forEach((room, index) => {
    params.set(`room[${index}].adults`, room.adults.toString())

    if (room.children) {
      room.children.forEach((child, childIndex) => {
        params.set(
          `room[${index}].child[${childIndex}].age`,
          child.age.toString()
        )
        params.set(
          `room[${index}].child[${childIndex}].bed`,
          child.bed.toString()
        )
      })
    }
  })
  return params
}
