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

import { useEnterDetailsStore } from "@/stores/enter-details"

import Button from "@/components/TempDesignSystem/Button"
import CountrySelect from "@/components/TempDesignSystem/Form/Country"
import Input from "@/components/TempDesignSystem/Form/Input"
import Phone from "@/components/TempDesignSystem/Form/Phone"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import { useRoomContext } from "@/contexts/Details/Room"

import JoinScandicFriendsCard from "./JoinScandicFriendsCard"
import MemberPriceModal from "./MemberPriceModal"
import { guestDetailsSchema, signedInDetailsSchema } from "./schema"
import Signup from "./Signup"
import SpecialRequests from "./SpecialRequests"

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

import type {
  DetailsProps,
  DetailsSchema,
} from "@/types/components/hotelReservation/enterDetails/details"

const formID = "enter-details"
export default function Details({ user }: DetailsProps) {
  const intl = useIntl()
  const [isMemberPriceModalOpen, setIsMemberPriceModalOpen] = useState(false)

  const { activeRoom, canProceedToPayment, lastRoom } = useEnterDetailsStore(
    (state) => ({
      activeRoom: state.activeRoom,
      canProceedToPayment: state.canProceedToPayment,
      lastRoom: state.lastRoom,
    })
  )
  const {
    actions: { updateDetails },
    room,
    roomNr,
  } = useRoomContext()
  const initialData = room.guest
  const memberRate = room.roomRate.memberRate

  const isPaymentNext = activeRoom === lastRoom

  const methods = useForm<DetailsSchema>({
    criteriaMode: "all",
    mode: "all",
    resolver: zodResolver(user ? signedInDetailsSchema : guestDetailsSchema),
    reValidateMode: "onChange",
    values: {
      countryCode: user?.address?.countryCode ?? initialData.countryCode,
      dateOfBirth: initialData.dateOfBirth,
      email: user?.email ?? initialData.email,
      firstName: user?.firstName ?? initialData.firstName,
      join: initialData.join,
      lastName: user?.lastName ?? initialData.lastName,
      membershipNo: initialData.membershipNo,
      phoneNumber: user?.phoneNumber ?? initialData.phoneNumber,
      zipCode: initialData.zipCode,
      specialRequests: initialData.specialRequests,
    },
  })

  const onSubmit = useCallback(
    (values: DetailsSchema) => {
      if ((values.join || values.membershipNo) && memberRate && !user) {
        setIsMemberPriceModalOpen(true)
      }
      updateDetails(values)
    },
    [updateDetails, setIsMemberPriceModalOpen, memberRate, user]
  )

  return (
    <FormProvider {...methods}>
      <form
        className={styles.form}
        id={`${formID}-room-${roomNr}`}
        onSubmit={methods.handleSubmit(onSubmit)}
      >
        {user ? null : <JoinScandicFriendsCard />}
        <div className={styles.container}>
          <Footnote
            color="uiTextHighContrast"
            textTransform="uppercase"
            type="label"
            className={styles.fullWidth}
          >
            {intl.formatMessage({ id: "Guest information" })}
          </Footnote>
          <Input
            label={intl.formatMessage({ id: "First name" })}
            maxLength={30}
            name="firstName"
            readOnly={!!user}
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({ id: "Last name" })}
            maxLength={30}
            name="lastName"
            readOnly={!!user}
            registerOptions={{ required: true }}
          />
          <CountrySelect
            className={styles.fullWidth}
            label={intl.formatMessage({ id: "Country" })}
            name="countryCode"
            readOnly={!!user}
            registerOptions={{ required: true }}
          />
          <Input
            className={styles.fullWidth}
            label={intl.formatMessage({ id: "Email address" })}
            name="email"
            readOnly={!!user}
            registerOptions={{ required: true }}
          />
          <Phone
            className={styles.fullWidth}
            label={intl.formatMessage({ id: "Phone number" })}
            name="phoneNumber"
            readOnly={!!user}
            registerOptions={{ required: true }}
          />
          {user ? null : (
            <div className={styles.fullWidth}>
              <Signup name="join" />
            </div>
          )}
          <SpecialRequests />
        </div>
        <footer className={styles.footer}>
          <Button
            disabled={
              !(
                methods.formState.isValid ||
                (isPaymentNext && canProceedToPayment)
              )
            }
            intent="secondary"
            size="small"
            theme="base"
            type="submit"
          >
            {isPaymentNext
              ? intl.formatMessage({ id: "Proceed to payment method" })
              : intl.formatMessage(
                { id: "Continue to room {nextRoomNumber}" },
                { nextRoomNumber: roomNr + 1 }
              )}
          </Button>
        </footer>
        <MemberPriceModal
          isOpen={isMemberPriceModalOpen}
          setIsOpen={setIsMemberPriceModalOpen}
        />
      </form>
    </FormProvider>
  )
}
