"use client"
import { useRouter } from "next/navigation"
import { useFormContext } from "react-hook-form"

import { selectHotel, selectRate } from "@/constants/routes/hotelReservation"

import useLang from "@/hooks/useLang"

import FormContent, { BookingWidgetFormContentSkeleton } from "./FormContent"
import { bookingWidgetVariants } from "./variants"

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

import type { BookingWidgetSchema } from "@/types/components/bookingWidget"
import type { BookingWidgetFormProps } from "@/types/components/form/bookingwidget"
import { Location } from "@/types/trpc/routers/hotel/locations"

const formId = "booking-widget"

export default function Form({
  locations,
  type,
  setIsOpen,
}: BookingWidgetFormProps) {
  const router = useRouter()
  const lang = useLang()

  const classNames = bookingWidgetVariants({
    type,
  })

  const { handleSubmit, register } = useFormContext<BookingWidgetSchema>()

  function onSubmit(data: BookingWidgetSchema) {
    const locationData: Location = JSON.parse(decodeURIComponent(data.location))

    const bookingFlowPage =
      locationData.type == "cities" ? selectHotel[lang] : selectRate[lang]
    const bookingWidgetParams = new URLSearchParams(data.date)

    if (locationData.type == "cities")
      bookingWidgetParams.set("city", locationData.name)
    else bookingWidgetParams.set("hotel", locationData.operaId || "")

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

      room.child.forEach((child, childIndex) => {
        bookingWidgetParams.set(
          `room[${index}].child[${childIndex}].age`,
          child.age.toString()
        )
        bookingWidgetParams.set(
          `room[${index}].child[${childIndex}].bed`,
          child.bed.toString()
        )
      })
    })
    setIsOpen(false)
    router.push(`${bookingFlowPage}?${bookingWidgetParams.toString()}`)
  }

  return (
    <section className={classNames}>
      <form
        onSubmit={handleSubmit(onSubmit)}
        className={styles.form}
        id={formId}
      >
        <input {...register("location")} type="hidden" />
        <FormContent locations={locations} formId={formId} />
      </form>
    </section>
  )
}

export function BookingWidgetFormSkeleton() {
  const classNames = bookingWidgetVariants({
    type: "full",
  })

  return (
    <section className={classNames}>
      <form className={styles.form}>
        <BookingWidgetFormContentSkeleton />
      </form>
    </section>
  )
}
