"use client"

import { useEffect, useState } from "react"
import { useFormContext, useWatch } from "react-hook-form"
import { useIntl } from "react-intl"

import MagicWandIcon from "@scandic-hotels/design-system/Icons/MagicWandIcon"

import Modal from "@/components/Modal"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import Title from "@/components/TempDesignSystem/Text/Title"
import { useRoomContext } from "@/contexts/Details/Room"
import { formatPrice } from "@/utils/numberFormatting"

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

import { CurrencyEnum } from "@/types/enums/currency"

export default function MemberPriceModal() {
  const {
    actions: { updatePriceForMembershipNo },
    room,
  } = useRoomContext()
  const memberRate = "member" in room.roomRate ? room.roomRate.member : null
  const intl = useIntl()
  const [isOpen, setIsOpen] = useState(false)
  const { getFieldState, trigger } = useFormContext()

  const [join, membershipNo] = useWatch({ name: ["join", "membershipNo"] })

  useEffect(() => {
    if (join) {
      setIsOpen(true)
    }
  }, [join])

  useEffect(() => {
    trigger("membershipNo").then((isValid) => {
      const { isDirty } = getFieldState("membershipNo")
      updatePriceForMembershipNo(membershipNo, isValid)
      if (isValid && isDirty) {
        setIsOpen(true)
      }
    })
  }, [getFieldState, membershipNo, trigger, updatePriceForMembershipNo])

  if (!memberRate) {
    return null
  }

  const memberPrice = memberRate?.localPrice ?? memberRate?.requestedPrice

  return (
    <Modal isOpen={isOpen} onToggle={() => setIsOpen(false)}>
      <div className={styles.modalContent}>
        <div className={styles.innerModalContent}>
          <MagicWandIcon width="265px" />
          <Title as="h3" level="h1" textTransform="regular">
            {intl.formatMessage({
              defaultMessage: "Member room price activated",
            })}
          </Title>

          {memberPrice && (
            <span className={styles.newPrice}>
              <Body>
                {intl.formatMessage({
                  defaultMessage: "The new price is",
                })}
              </Body>
              <Subtitle type="two" color="red">
                {formatPrice(
                  intl,
                  memberPrice.pricePerStay ?? 0,
                  memberPrice.currency ?? CurrencyEnum.Unknown
                )}
              </Subtitle>
            </span>
          )}
        </div>
        <Button intent="primary" theme="base" onClick={() => setIsOpen(false)}>
          {intl.formatMessage({
            defaultMessage: "OK",
          })}
        </Button>
      </div>
    </Modal>
  )
}
