"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 { myStay } from "@/constants/routes/myStay"
import { customerService } from "@/constants/webHrefs"
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>({
    defaultValues: {
      confirmationNumber: "",
      firstName: "",
      lastName: "",
      email: "",
    },
    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=${encodeURIComponent(value)}; Path=/; Max-Age=600; Secure; SameSite=Strict`
      router.push(`${myStay[lang]}?RefId=${encodeURIComponent(result.refId)}`)
    },
    onError: (error) => {
      console.error("Failed to create ref id", error)
      toast.error(
        intl.formatMessage({
          defaultMessage: "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({
              defaultMessage: "Find your stay",
            })}
          </Title>
          <Body>
            {intl.formatMessage({
              defaultMessage:
                "View and manage your booking made via our website or app.",
            })}
          </Body>
        </div>
        <div className={[styles.inputs, styles.grid].join(" ")}>
          <Input
            label={intl.formatMessage({
              defaultMessage: "Booking number",
            })}
            name="confirmationNumber"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({
              defaultMessage: "First name",
            })}
            name="firstName"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({
              defaultMessage: "Last name",
            })}
            name="lastName"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({
              defaultMessage: "Email",
            })}
            name="email"
            type="email"
            registerOptions={{ required: true }}
          />
        </div>
        <div className={styles.buttons}>
          <div className={styles.footnote}>
            <Caption type="bold">
              {intl.formatMessage({
                defaultMessage: "Can't find your stay?",
              })}
            </Caption>
            <Caption>
              {intl.formatMessage(
                {
                  defaultMessage:
                    "Please contact <link>customer service</link>.",
                },
                {
                  link: (str) => (
                    <Link
                      href={customerService[lang]}
                      size="small"
                      textDecoration="underline"
                      target="_blank"
                    >
                      {str}
                    </Link>
                  ),
                }
              )}
            </Caption>
          </div>
          <Button
            type="submit"
            intent="primary"
            theme="base"
            disabled={form.formState.isSubmitting || update.isPending}
          >
            {intl.formatMessage({
              defaultMessage: "Find",
            })}
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
