import { useFormContext } from "react-hook-form"
import { useIntl } from "react-intl"

import { useAddAncillaryStore } from "@/stores/my-stay/add-ancillary-flow"

import { DiamondIcon } from "@/components/Icons"
import ErrorMessage from "@/components/TempDesignSystem/Form/ErrorMessage"
import Select from "@/components/TempDesignSystem/Form/Select"
import Body from "@/components/TempDesignSystem/Text/Body"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"

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

import type { SelectQuantityStepProps } from "@/types/components/myPages/myStay/ancillaries"

export default function SelectQuantityStep({ user }: SelectQuantityStepProps) {
  const intl = useIntl()
  const { selectedAncillary } = useAddAncillaryStore()
  const { formState } = useFormContext()

  const cardQuantityOptions = Array.from({ length: 7 }, (_, i) => ({
    label: `${i}`,
    value: i,
  }))

  const pointsCost = selectedAncillary?.points ?? 0
  const currentPoints = user?.membership?.currentPoints ?? 0
  const maxAffordable =
    pointsCost > 0 ? Math.min(Math.floor(currentPoints / pointsCost), 7) : 0

  const pointsQuantityOptions = Array.from(
    { length: maxAffordable + 1 },
    (_, i) => ({
      label: `${i}`,
      value: i,
    })
  )

  const insufficientPoints = currentPoints < pointsCost || currentPoints === 0

  const pointsLabel =
    insufficientPoints && user
      ? intl.formatMessage({ id: "Insufficient points" })
      : intl.formatMessage({ id: "Select quantity" })

  return (
    <div className={styles.selectContainer}>
      {selectedAncillary?.points && user && (
        <div className={styles.select}>
          <Subtitle type="two">
            {intl.formatMessage({ id: "Pay with points" })}
          </Subtitle>
          <div className={styles.totalPointsContainer}>
            <div className={styles.totalPoints}>
              <DiamondIcon />
              <Subtitle textTransform="uppercase" type="two">
                {intl.formatMessage({ id: "Total points" })}
              </Subtitle>
            </div>
            <Body>{currentPoints}</Body>
          </div>
          <Select
            name="quantityWithPoints"
            label={pointsLabel}
            items={pointsQuantityOptions}
            disabled={!user || insufficientPoints}
            isNestedInModal
          />
        </div>
      )}
      <div className={styles.select}>
        <Subtitle type="two">
          {intl.formatMessage({ id: "Pay with Card" })}
        </Subtitle>
        <Select
          name="quantityWithCard"
          label={intl.formatMessage({ id: "Select quantity" })}
          items={cardQuantityOptions}
          isNestedInModal
        />
      </div>
      <ErrorMessage errors={formState.errors} name="quantityWithCard" />
    </div>
  )
}
