"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=${encodeURIComponent(value)}; Path=/; Max-Age=600; Secure; SameSite=Strict`
    router.refresh()
  }

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