"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 "@scandic-hotels/common/constants/routes/myStay"
import { logger } from "@scandic-hotels/common/logger"
import Body from "@scandic-hotels/design-system/Body"
import Caption from "@scandic-hotels/design-system/Caption"
import { OldDSButton as Button } from "@scandic-hotels/design-system/OldDSButton"
import Title from "@scandic-hotels/design-system/Title"
import { trpc } from "@scandic-hotels/trpc/client"

import { customerService } from "@/constants/webHrefs"

import Input from "@/components/TempDesignSystem/Form/Input"
import Link from "@/components/TempDesignSystem/Link"
import { toast } from "@/components/TempDesignSystem/Toasts"
import useLang from "@/hooks/useLang"

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

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

import type { AdditionalInfoCookieValue } from "./AdditionalInfoForm"

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: AdditionalInfoCookieValue = {
        ...values,
      }
      document.cookie = `bv=${JSON.stringify(value)}; Path=/; Max-Age=600; Secure; SameSite=Strict`
      router.push(`${myStay[lang]}?RefId=${encodeURIComponent(result.refId)}`)
    },
    onError: (error) => {
      logger.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>
  )
}
