"use client"
import { useRouter } from "next/navigation"
import { Form as FormRAC } from "react-aria-components"
import { useFormContext } from "react-hook-form"

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

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

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 type { Location } from "@/types/trpc/routers/hotel/locations"

const formId = "booking-widget"

export default function Form({
  locations,
  type,
  onClose,
}: 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 = convertObjToSearchParams({
      rooms: data.rooms,
      ...data.date,
      ...(locationData.type == "cities"
        ? { city: locationData.name }
        : { hotel: locationData.operaId || "" }),
    })

    onClose()
    router.push(`${bookingFlowPage}?${bookingWidgetParams.toString()}`)
  }

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

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

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