"use client"
import { useRouter } from "next/navigation"
import { useTransition } from "react"
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 [isPending, startTransition] = useTransition()

  const classNames = bookingWidgetVariants({
    type,
  })

  const { handleSubmit, register, setValue } =
    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 || "" }),
      ...(data.bookingCode?.value
        ? { bookingCode: data.bookingCode.value }
        : {}),
    })

    onClose()
    startTransition(() => {
      router.push(`${bookingFlowPage}?${bookingWidgetParams.toString()}`)
    })
    if (!data.bookingCode?.value) {
      setValue("bookingCode.remember", false)
      localStorage.removeItem("bookingCode")
    } else if (data.bookingCode?.remember) {
      localStorage.setItem("bookingCode", JSON.stringify(data.bookingCode))
    }
  }

  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)}
          isSearching={isPending}
        />
      </FormRAC>
    </section>
  )
}

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

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