"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 "@scandic-hotels/design-system/Button"

import Input from "@/components/TempDesignSystem/Form/Input"

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

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

import type { AdditionalInfoCookieValue } from "@scandic-hotels/booking-flow/types/components/findMyBooking/additionalInfoCookieValue"

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

  function onSubmit() {
    const values = form.getValues()
    const value: AdditionalInfoCookieValue = {
      ...values,
      confirmationNumber,
      lastName,
    }
    document.cookie = `bv=${JSON.stringify(value)}; Path=/; Max-Age=600; Secure; SameSite=Strict`
    router.refresh()
  }

  return (
    <FormProvider {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className={styles.form}>
        <Title isAdditional />
        <div className={styles.inputs}>
          <Input
            label={intl.formatMessage({
              id: "common.firstName",
              defaultMessage: "First name",
            })}
            name="firstName"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({
              id: "common.email",
              defaultMessage: "Email",
            })}
            name="email"
            type="email"
            registerOptions={{ required: true }}
          />
        </div>
        <div className={styles.buttons}>
          <Button
            type="submit"
            variant="Primary"
            size="Medium"
            isDisabled={form.formState.isSubmitting}
          >
            {intl.formatMessage({
              id: "common.confirm",
              defaultMessage: "Confirm",
            })}
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
