"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 { trpc } from "@/lib/trpc/client"

import Button from "@/components/TempDesignSystem/Button"
import Input from "@/components/TempDesignSystem/Form/Input"
import Link from "@/components/TempDesignSystem/Link"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Title from "@/components/TempDesignSystem/Text/Title"
import useLang from "@/hooks/useLang"

import { type FindMyBookingFormSchema, findMyBookingFormSchema } from "./schema"

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

export default function Form() {
  const router = useRouter()
  const intl = useIntl()
  const lang = useLang()
  const form = useForm<FindMyBookingFormSchema>({
    defaultValues: {
      reservationNumber: "",
      firstName: "",
      lastName: "",
      email: "",
    },
    resolver: zodResolver(findMyBookingFormSchema),
    mode: "all",
    criteriaMode: "all",
    reValidateMode: "onChange",
  })

  const update = trpc.booking.createRefId.useMutation({
    onSuccess: (result) => {
      router.push(
        `/${lang}/hotelreservation/my-stay/${encodeURIComponent(result.refId)}`
      )
    },
    onError: (error) => {
      console.log("Failed to create ref id", error)
    },
  })

  async function onSubmit(data: FindMyBookingFormSchema) {
    const value = new URLSearchParams(data).toString()
    document.cookie = `bv=${value}; Path=/; Max-Age=30; Secure; SameSite=Strict`
    update.mutate({
      confirmationNumber: data.reservationNumber,
      lastName: data.lastName,
    })
  }
  return (
    <FormProvider {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className={styles.form}>
        <div>
          <Title level="h2">
            {intl.formatMessage({ id: "Find your stay" })}
          </Title>
          <Body>
            {intl.formatMessage({
              id: "View and manage your stay made on Scandic's website",
            })}
          </Body>
        </div>
        <div className={styles.inputs}>
          <Input
            label="Reservation number"
            name="reservationNumber"
            placeholder="XXXXXX"
            registerOptions={{ required: true }}
          />
          <Input
            label="First name"
            name="firstName"
            placeholder="Anna"
            registerOptions={{ required: true }}
          />
          <Input
            label="Last name"
            name="lastName"
            placeholder="Andersson"
            registerOptions={{ required: true }}
          />
          <Input
            label="Email"
            name="email"
            placeholder="anna@scandichotels.com"
            registerOptions={{ required: true }}
          />
        </div>
        <div className={styles.buttons}>
          <div className={styles.footnote}>
            <Caption type="bold">
              {intl.formatMessage({ id: "Can't find your stay?" })}
            </Caption>
            <Caption>
              {intl.formatMessage<React.ReactNode>(
                { id: "Please call customer service at {phoneNr}" },
                { phoneNr: <Link href="tel:XXXXXX">XXXXXX</Link> }
              )}
            </Caption>
          </div>
          <Button
            type="submit"
            intent="primary"
            theme="base"
            disabled={form.formState.isSubmitting}
          >
            {intl.formatMessage({ id: "Find" })}
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
