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

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 { getDefaultCountryFromLang } from "@/constants/languages"
import { useEnterDetailsStore } from "@/stores/enter-details"

import SpecialRequests from "@/components/HotelReservation/EnterDetails/Details/SpecialRequests"
import Input from "@/components/TempDesignSystem/Form/Input"
import { useFormTracking } from "@/components/TrackingSDK/hooks"
import { useRoomContext } from "@/contexts/Details/Room"
import useLang from "@/hooks/useLang"
import usePhoneNumberParsing from "@/hooks/usePhoneNumberParsing"
import { getFormattedCountryList } from "@/utils/countries"
import { getErrorMessage } from "@/utils/getErrorMessage"

import MemberPriceModal from "../MemberPriceModal"
import JoinScandicFriendsCard from "./JoinScandicFriendsCard"
import { getMultiroomDetailsSchema } from "./schema"

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

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

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

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

  /**
   * The data that each room needs from each other to do validations
   * across the rooms
   */
  const crossValidationData = useMemo(
    () =>
      rooms
        .filter((_, i) => i !== idx)
        .map((room) => ({
          firstName: room.room.guest.firstName,
          lastName: room.room.guest.lastName,
          membershipNo: room.room.guest.membershipNo,
        })),
    [idx, rooms]
  )

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

  const methods = useForm({
    defaultValues: {
      countryCode: initialData.countryCode,
      email: initialData.email,
      firstName: initialData.firstName,
      join: initialData.join,
      lastName: initialData.lastName,
      membershipNo: initialData.membershipNo,
      phoneNumber,
      phoneNumberCC,
      specialRequest: {
        comment: room.specialRequest.comment,
      },
    },
    criteriaMode: "all",
    mode: "onBlur",
    resolver: zodResolver(getMultiroomDetailsSchema(crossValidationData)),
    reValidateMode: "onChange",
  })

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

  const { trackFormSubmit } = useFormTracking(
    "checkout",
    subscribe,
    control,
    ` - room ${roomNr}`
  )

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

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

  useEffect(updateDetailsStore, [updateDetailsStore])

  // Trigger validation of the room manually when another room changes its data.
  // Only do it if the field has a value, to avoid error states before the user
  // has filled anything in.
  useEffect(() => {
    const { firstName, lastName, membershipNo } = methods.getValues()
    if (firstName) {
      methods.trigger("firstName")
    }
    if (lastName) {
      methods.trigger("lastName")
    }
    if (membershipNo) {
      methods.trigger("membershipNo")
    }
  }, [crossValidationData, methods])

  const countryCode = watch("countryCode")

  useEffect(() => {
    if (countryCode) {
      setValue("phoneNumberCC", countryCode.toLowerCase())
    }
  }, [countryCode, setValue])

  const guestIsGoingToJoin = methods.watch("join")
  const guestIsMember = methods.watch("membershipNo")

  return (
    <FormProvider {...methods}>
      <form
        className={styles.form}
        id={`${formID}-room-${roomNr}`}
        onSubmit={methods.handleSubmit(updateDetails)}
      >
        {guestIsMember ? null : <JoinScandicFriendsCard />}
        <div className={styles.container}>
          <Footnote
            color="uiTextHighContrast"
            textTransform="uppercase"
            type="label"
            className={styles.fullWidth}
          >
            {intl.formatMessage({
              defaultMessage: "Guest information",
            })}
          </Footnote>
          <Input
            label={intl.formatMessage({
              defaultMessage: "First name",
            })}
            maxLength={30}
            name="firstName"
            registerOptions={{
              required: true,
              deps: "lastName",
              onBlur: updateDetailsStore,
            }}
          />
          <Input
            label={intl.formatMessage({
              defaultMessage: "Last name",
            })}
            maxLength={30}
            name="lastName"
            registerOptions={{
              required: true,
              deps: "firstName",
              onBlur: updateDetailsStore,
            }}
          />
          <CountrySelect
            className={styles.fullWidth}
            countries={getFormattedCountryList(intl)}
            errorMessage={getErrorMessage(intl, errors.countryCode?.message)}
            label={intl.formatMessage({
              defaultMessage: "Country",
            })}
            lang={lang}
            name="countryCode"
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          <Input
            className={styles.fullWidth}
            label={intl.formatMessage({
              defaultMessage: "Email address",
            })}
            name="email"
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          <Phone
            countryLabel={intl.formatMessage({
              defaultMessage: "Country code",
            })}
            countriesWithTranslatedName={getFormattedCountryList(intl)}
            defaultCountryCode={getDefaultCountryFromLang(lang)}
            errorMessage={getErrorMessage(intl, errors.phoneNumber?.message)}
            className={styles.fullWidth}
            label={intl.formatMessage({
              defaultMessage: "Phone number",
            })}
            name="phoneNumber"
            registerOptions={{ required: true, onBlur: updateDetailsStore }}
          />
          {guestIsGoingToJoin ? null : (
            <Input
              className={styles.fullWidth}
              label={intl.formatMessage({
                defaultMessage: "Membership ID",
              })}
              name="membershipNo"
              type="tel"
              registerOptions={{ onBlur: updateDetailsStore }}
            />
          )}
          <SpecialRequests registerOptions={{ onBlur: updateDetailsStore }} />
        </div>
        <MemberPriceModal />
      </form>
    </FormProvider>
  )
}
