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

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

import SpecialRequests from "@/components/HotelReservation/EnterDetails/Details/SpecialRequests"
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 { multiroomDetailsSchema } from "./schema"

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

import type { MultiroomDetailsSchema } from "@/types/components/hotelReservation/enterDetails/details"

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

  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 isPaymentNext = activeRoom === lastRoom

  const methods = useForm<MultiroomDetailsSchema>({
    criteriaMode: "all",
    mode: "all",
    resolver: zodResolver(multiroomDetailsSchema),
    reValidateMode: "onChange",
    values: {
      countryCode: initialData.countryCode,
      email: initialData.email,
      firstName: initialData.firstName,
      join: initialData.join,
      lastName: initialData.lastName,
      membershipNo: initialData.membershipNo,
      phoneNumber: initialData.phoneNumber,
      specialRequest: {
        comment: room.specialRequest.comment,
      },
    },
  })

  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({ id: "Guest information" })}
          </Footnote>
          <Input
            label={intl.formatMessage({ id: "First name" })}
            maxLength={30}
            name="firstName"
            registerOptions={{ required: true }}
          />
          <Input
            label={intl.formatMessage({ id: "Last name" })}
            maxLength={30}
            name="lastName"
            registerOptions={{ required: true }}
          />
          <CountrySelect
            className={styles.fullWidth}
            label={intl.formatMessage({ id: "Country" })}
            name="countryCode"
            registerOptions={{ required: true }}
          />
          <Input
            className={styles.fullWidth}
            label={intl.formatMessage({ id: "Email address" })}
            name="email"
            registerOptions={{ required: true }}
          />
          <Phone
            className={styles.fullWidth}
            label={intl.formatMessage({ id: "Phone number" })}
            name="phoneNumber"
            registerOptions={{ required: true }}
          />
          {guestIsGoingToJoin ? null : (
            <Input
              className={styles.fullWidth}
              label={intl.formatMessage({ id: "Membership no" })}
              name="membershipNo"
              type="tel"
            />
          )}
          <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>
      </form>
    </FormProvider>
  )
}
