"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"

import Button from "@/components/TempDesignSystem/Button"
import Input from "@/components/TempDesignSystem/Form/Input"
import Body from "@/components/TempDesignSystem/Text/Body"
import Title from "@/components/TempDesignSystem/Text/Title"

import {
  type AdditionalInfoFormSchema,
  additionalInfoFormSchema,
} from "./schema"

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

export default function AdditionalInfoForm({
  confirmationNumber,
  lastName,
}: {
  confirmationNumber: string
  lastName: string
}) {
  const router = useRouter()
  const intl = useIntl()
  const form = useForm<AdditionalInfoFormSchema>({
    resolver: zodResolver(additionalInfoFormSchema),
    mode: "all",
    criteriaMode: "all",
    reValidateMode: "onChange",
  })

  function onSubmit() {
    const values = form.getValues()
    const value = new URLSearchParams({
      ...values,
      confirmationNumber,
      lastName,
    }).toString()
    document.cookie = `bv=${value}; Path=/; Max-Age=30; Secure; SameSite=Strict`
    router.refresh()
  }

  return (
    <FormProvider {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className={styles.form}>
        <div>
          <Title level="h2" as="h3">
            {intl.formatMessage({
              id: "One last step",
            })}
          </Title>
          <Body>
            {intl.formatMessage({
              id: "We need some more details to confirm your identity.",
            })}
          </Body>
        </div>
        <div className={styles.inputs}>
          <Input
            label={intl.formatMessage({ id: "First name" })}
            name="firstName"
            placeholder="Anna"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({ id: "Email" })}
            name="email"
            placeholder="anna@scandichotels.com"
            registerOptions={{ required: true }}
          />
        </div>
        <div className={styles.buttons}>
          <Button
            type="submit"
            intent="primary"
            theme="base"
            disabled={form.formState.isSubmitting}
          >
            {intl.formatMessage({ id: "Confirm" })}
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
