"use client"
import { useRef, useState } from "react"
import { Button } from "react-aria-components"
import { useIntl } from "react-intl"

import { CheckIcon, InfoCircleIcon } from "@/components/Icons"
import Label from "@/components/TempDesignSystem/Form/Label"
import Caption from "@/components/TempDesignSystem/Text/Caption"

import PricePopover from "./Popover"
import PriceTable from "./PriceList"

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

import { FlexibilityOptionProps } from "@/types/components/hotelReservation/selectRate/flexibilityOption"

export default function FlexibilityOption({
  product,
  name,
  paymentTerm,
  priceInformation,
  roomType,
  roomTypeCode,
  features,
  petRoomPackage,
  handleSelectRate,
}: FlexibilityOptionProps) {
  const [rootDiv, setRootDiv] = useState<Element | undefined>(undefined)
  const [isPopoverOpen, setIsPopoverOpen] = useState(false)
  let triggerRef = useRef<HTMLButtonElement>(null)
  const buttonClickedRef = useRef(false)
  const intl = useIntl()

  function setRef(node: Element | null) {
    if (node) {
      setRootDiv(node)
    }
  }

  if (!product) {
    return (
      <div className={styles.noPricesCard}>
        <div className={styles.header}>
          <InfoCircleIcon width={16} height={16} color="uiTextMediumContrast" />
          <Caption>{name}</Caption>
          <Caption color="uiTextPlaceholder">({paymentTerm})</Caption>
        </div>
        <Label size="regular" className={styles.noPricesLabel}>
          <Caption color="uiTextHighContrast" type="bold">
            {intl.formatMessage({ id: "No Prices available" })}
          </Caption>
        </Label>
      </div>
    )
  }

  const { public: publicPrice, member: memberPrice } = product.productType

  function onChange() {
    const rate = {
      roomTypeCode,
      roomType,
      priceName: name,
      public: publicPrice,
      member: memberPrice,
      features: petRoomPackage ? features : [],
    }
    handleSelectRate(rate)
  }

  function togglePopover() {
    buttonClickedRef.current = !buttonClickedRef.current
    setIsPopoverOpen(buttonClickedRef.current)
  }

  function handlePopoverChange(isOpen: boolean) {
    setIsPopoverOpen(isOpen)
  }

  return (
    <label>
      <input
        type="radio"
        name="rateCode"
        value={publicPrice?.rateCode}
        onChange={onChange}
      />
      <div className={styles.card}>
        <div className={styles.header} ref={setRef}>
          <Button
            aria-label="Help"
            className={styles.button}
            onPress={() => {
              togglePopover()
            }}
            ref={triggerRef}
          >
            <InfoCircleIcon
              width={16}
              height={16}
              color="uiTextMediumContrast"
            />
          </Button>
          <PricePopover
            placement="bottom"
            className={styles.popover}
            isNonModal
            shouldFlip={false}
            shouldUpdatePosition={false}
            /**
             * react-aria uses portals to render Popover in body
             * unless otherwise specified. We need it to be contained
             * by this component to both access css variables assigned
             * on the container as well as to not overflow it at any time.
             */
            UNSTABLE_portalContainer={rootDiv}
            triggerRef={triggerRef}
            isOpen={isPopoverOpen}
            onOpenChange={handlePopoverChange}
          >
            <Caption
              color="uiTextHighContrast"
              type="bold"
              className={styles.popoverHeading}
            >
              {name}
            </Caption>
            {priceInformation?.map((info) => (
              <Caption
                key={info}
                color="uiTextHighContrast"
                className={styles.popoverText}
              >
                {info}
              </Caption>
            ))}
          </PricePopover>
          <Caption color="uiTextHighContrast">{name}</Caption>
          <Caption color="uiTextPlaceholder">({paymentTerm})</Caption>
        </div>
        <PriceTable
          publicPrice={publicPrice}
          memberPrice={memberPrice}
          petRoomPackage={petRoomPackage}
        />

        <div className={styles.checkIcon}>
          <CheckIcon color="white" height="16" width="16" />
        </div>
      </div>
    </label>
  )
}
