"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 { customerService } from "@/constants/currentWebHrefs"
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 { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"

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

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

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

  const update = trpc.booking.createRefId.useMutation({
    onSuccess: (result) => {
      const values = form.getValues()
      const value = new URLSearchParams(values).toString()
      document.cookie = `bv=${value}; Path=/; Max-Age=30; Secure; SameSite=Strict`
      router.push(
        `/${lang}/hotelreservation/my-stay/${encodeURIComponent(result.refId)}`
      )
    },
    onError: (error) => {
      console.error("Failed to create ref id", error)
      toast.error(
        intl.formatMessage({
          id: "Failed to submit form, please try again later.",
        })
      )
    },
  })

  async function onSubmit(data: FindMyBookingFormSchema) {
    update.mutate({
      confirmationNumber: data.confirmationNumber,
      lastName: data.lastName,
    })
  }

  return (
    <FormProvider {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className={styles.form}>
        <div>
          <Title level="h2" as="h3">
            {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, styles.grid].join(" ")}>
          <Input
            label={intl.formatMessage({ id: "Booking number" })}
            name="confirmationNumber"
            placeholder="XXXXXX"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({ id: "First name" })}
            name="firstName"
            placeholder="Anna"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({ id: "Last name" })}
            name="lastName"
            placeholder="Andersson"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({ id: "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(
                { id: "Please contact <link>customer service</link>." },
                {
                  link: (str) => (
                    <Link
                      href={customerService[lang]}
                      size="small"
                      color="uiTextPlaceholder"
                      textDecoration="underline"
                      target="_blank"
                    >
                      {str}
                    </Link>
                  ),
                }
              )}
            </Caption>
          </div>
          <Button
            type="submit"
            intent="primary"
            theme="base"
            disabled={form.formState.isSubmitting || update.isPending}
          >
            {intl.formatMessage({ id: "Find" })}
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
