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

import Button from "@/components/TempDesignSystem/Button"
import Caption from "@/components/TempDesignSystem/Text/Caption"

import FormContent from "./FormContent"

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

import type { BookingWidgetSchema } from "@/types/components/bookingWidget"
import type { BookingWidgetFormProps } from "@/types/components/form/bookingwidget"

const formId = "booking-widget"

export default function Form({ locations }: BookingWidgetFormProps) {
  const intl = useIntl()
  const router = useRouter()

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

  function onSubmit(data: BookingWidgetSchema) {
    data.location = JSON.parse(decodeURIComponent(data.location))
    console.log(data)
    // TODO: Parse data and route accordignly to Select hotel or select room-rate page
    console.log("to be routing")
    router.push("/en/hotelreservation/select-hotel")
  }

  return (
    <section className={styles.section}>
      <form
        onSubmit={handleSubmit(onSubmit)}
        className={styles.form}
        id={formId}
      >
        <input {...register("location")} type="hidden" />
        <FormContent locations={locations} />
      </form>
      <Button
        className={styles.button}
        disabled={!formState.isValid}
        form={formId}
        intent="primary"
        size="small"
        theme="base"
        type="submit"
      >
        <Caption color="white" textTransform="bold">
          {intl.formatMessage({ id: "Search" })}
        </Caption>
      </Button>
    </section>
  )
}
