"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useCallback, useEffect } from "react"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"

import { usePhoneNumberParsing } from "@scandic-hotels/common/hooks/usePhoneNumberParsing"
import { getDefaultCountryFromLang } from "@scandic-hotels/common/utils/phone"
import Footnote from "@scandic-hotels/design-system/Footnote"
import CountrySelect from "@scandic-hotels/design-system/Form/Country"
import Phone from "@scandic-hotels/design-system/Form/Phone"
import { useFormTracking } from "@scandic-hotels/tracking/useFormTracking"

import { useRoomContext } from "../../../../contexts/EnterDetails/RoomContext"
import useLang from "../../../../hooks/useLang"
import { getFormattedCountryList } from "../../../../misc/getFormatedCountryList"
import { useEnterDetailsStore } from "../../../../stores/enter-details"
import BookingFlowInput from "../../../BookingFlowInput"
import { getErrorMessage } from "../../../BookingFlowInput/errors"
import MemberPriceModal from "../MemberPriceModal"
import { SpecialRequests } from "../SpecialRequests"
import JoinScandicFriendsCard from "./JoinScandicFriendsCard"
import {
  type GuestDetailsSchema,
  guestDetailsSchema,
  signedInDetailsSchema,
} from "./schema"
import Signup from "./Signup"

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

import type { User } from "@scandic-hotels/trpc/types/user"

type DetailsProps = {
  user: User | null
}

const formID = "enter-details"
export default function Details({ user }: DetailsProps) {
  const intl = useIntl()
  const lang = useLang()

  const { lastRoom, addPreSubmitCallback } = useEnterDetailsStore((state) => ({
    lastRoom: state.lastRoom,
    addPreSubmitCallback: state.actions.addPreSubmitCallback,
  }))

  const {
    actions: { updateDetails, updatePartialGuestData, setIncomplete },
    room,
    roomNr,
    idx,
  } = useRoomContext()

  const initialData = room.guest

  const memberRate = "member" in room.roomRate ? room.roomRate.member : null

  const { phoneNumber, phoneNumberCC } = usePhoneNumberParsing(
    user?.phoneNumber || initialData.phoneNumber,
    initialData.phoneNumberCC
  )

  const methods = useForm({
    defaultValues: {
      countryCode: user?.address?.countryCode || initialData.countryCode,
      dateOfBirth:
        "dateOfBirth" in initialData ? initialData.dateOfBirth : undefined,
      email: user?.email || initialData.email,
      firstName: user?.firstName || initialData.firstName,
      join: initialData.join,
      lastName: user?.lastName || initialData.lastName,
      membershipNo: initialData.membershipNo,
      phoneNumber,
      phoneNumberCC,
      zipCode: "zipCode" in initialData ? initialData.zipCode : undefined,
      specialRequest: {
        comment: room.specialRequest.comment,
      },
    },
    criteriaMode: "all",
    mode: "onBlur",
    resolver: zodResolver(user ? signedInDetailsSchema : guestDetailsSchema),
    reValidateMode: "onChange",
  })

  const {
    formState,
    handleSubmit,
    trigger,
    control,
    subscribe,
    setValue,
    watch,
    getValues,
  } = methods

  const { trackFormSubmit } = useFormTracking(
    "checkout",
    subscribe,
    control,
    lastRoom === idx ? "" : " - room 1"
  )

  useEffect(() => {
    function callback() {
      trigger()
      trackFormSubmit()
    }
    addPreSubmitCallback(`${idx}-details`, callback)
  }, [addPreSubmitCallback, idx, trigger, trackFormSubmit])

  const onSubmit = useCallback(
    (values: GuestDetailsSchema) => {
      updateDetails(values)
    },
    [updateDetails]
  )

  const updateDetailsStore = useCallback(() => {
    if (formState.isValid) {
      handleSubmit(onSubmit)()
    } else {
      updatePartialGuestData({
        firstName: getValues("firstName")?.toString(),
        lastName: getValues("lastName")?.toString(),
        membershipNo: getValues("membershipNo")?.toString(),
      })
      setIncomplete()
    }
  }, [
    handleSubmit,
    formState.isValid,
    onSubmit,
    setIncomplete,
    updatePartialGuestData,
    getValues,
  ])

  useEffect(updateDetailsStore, [updateDetailsStore])
  const countryCode = watch("countryCode")

  useEffect(() => {
    if (countryCode) {
      setValue("phoneNumberCC", countryCode.toLowerCase())
    }
  }, [countryCode, setValue])
  return (
    <FormProvider {...methods}>
      <form
        className={styles.form}
        id={`${formID}-room-${roomNr}`}
        onSubmit={methods.handleSubmit(onSubmit)}
      >
        {user || !memberRate ? null : <JoinScandicFriendsCard />}
        <div className={styles.container}>
          <Footnote
            color="uiTextHighContrast"
            textTransform="uppercase"
            type="label"
            className={styles.fullWidth}
          >
            {intl.formatMessage({
              defaultMessage: "Guest information",
            })}
          </Footnote>
          <BookingFlowInput
            autoComplete="given-name"
            label={intl.formatMessage({
              defaultMessage: "First name",
            })}
            maxLength={30}
            name="firstName"
            readOnly={!!user}
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          <BookingFlowInput
            autoComplete="family-name"
            label={intl.formatMessage({
              defaultMessage: "Last name",
            })}
            maxLength={30}
            name="lastName"
            readOnly={!!user}
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          <CountrySelect
            className={styles.fullWidth}
            label={intl.formatMessage({
              defaultMessage: "Country",
            })}
            lang={lang}
            countries={getFormattedCountryList(intl)}
            errorMessage={getErrorMessage(
              intl,
              formState.errors.countryCode?.message
            )}
            name="countryCode"
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
            disabled={!!user}
          />
          <BookingFlowInput
            autoComplete="email"
            className={styles.fullWidth}
            label={intl.formatMessage({
              defaultMessage: "Email address",
            })}
            name="email"
            readOnly={!!user}
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          <Phone
            className={styles.fullWidth}
            countryLabel={intl.formatMessage({
              defaultMessage: "Country code",
            })}
            countriesWithTranslatedName={getFormattedCountryList(intl)}
            defaultCountryCode={getDefaultCountryFromLang(lang)}
            errorMessage={getErrorMessage(
              intl,
              formState.errors.phoneNumber?.message
            )}
            label={intl.formatMessage({
              defaultMessage: "Phone number",
            })}
            name="phoneNumber"
            disabled={!!user}
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          {user ? null : (
            <div className={styles.fullWidth}>
              <Signup
                errors={formState.errors}
                name="join"
                registerOptions={{ onBlur: updateDetailsStore }}
              />
            </div>
          )}
          <SpecialRequests registerOptions={{ onBlur: updateDetailsStore }} />
        </div>
        <MemberPriceModal />
      </form>
    </FormProvider>
  )
}
