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

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"

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

import Alert from "@/components/TempDesignSystem/Alert"
import ErrorMessage from "@/components/TempDesignSystem/Form/ErrorMessage"
import Select from "@/components/TempDesignSystem/Form/Select"
import Body from "@/components/TempDesignSystem/Text/Body"

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

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

export default function SelectQuantityStep({ user }: SelectQuantityStepProps) {
  const intl = useIntl()
  const { isBreakfast, selectedAncillary } = useAddAncillaryStore((state) => ({
    isBreakfast: state.isBreakfast,
    selectedAncillary: state.selectedAncillary,
  }))
  const {
    formState: { errors },
  } = useFormContext()

  if (isBreakfast) {
    return <BreakfastInfo />
  }

  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

  return (
    <div className={styles.selectContainer}>
      {selectedAncillary?.points && user && (
        <div className={styles.select}>
          <Typography variant="Title/Subtitle/md">
            <h2 className={styles.selectTitle}>
              {intl.formatMessage({
                defaultMessage: "Pay with points",
              })}
            </h2>
          </Typography>
          <div className={styles.totalPointsContainer}>
            <div className={styles.totalPoints}>
              <MaterialIcon icon="diamond" />
              <Typography variant="Title/Overline/sm">
                <h2>
                  {intl.formatMessage({
                    defaultMessage: "Total points",
                  })}
                </h2>
              </Typography>
            </div>
            <Typography variant="Body/Paragraph/mdRegular">
              <p>{currentPoints}</p>
            </Typography>
          </div>
          {insufficientPoints ? (
            <Typography variant="Body/Supporting text (caption)/smRegular">
              <h2 className={styles.insufficientPoints}>
                {intl.formatMessage({
                  defaultMessage: "Insufficient points",
                })}
              </h2>
            </Typography>
          ) : (
            <Select
              name="quantityWithPoints"
              label={intl.formatMessage({
                defaultMessage: "Select quantity",
              })}
              items={pointsQuantityOptions}
              isNestedInModal
            />
          )}
        </div>
      )}
      <div className={styles.select}>
        <Typography variant="Title/Subtitle/md">
          <h2 className={styles.selectTitle}>
            {
              /* eslint-disable-next-line formatjs/no-literal-string-in-jsx */
              " "
            }
            {intl.formatMessage({
              defaultMessage: "Pay with card at the hotel",
            })}
          </h2>
        </Typography>
        <Select
          name="quantityWithCard"
          label={intl.formatMessage({
            defaultMessage: "Select quantity",
          })}
          items={cardQuantityOptions}
          isNestedInModal
        />
        <ErrorMessage errors={errors} name="quantityWithCard" />
      </div>
    </div>
  )
}

function BreakfastInfo() {
  const intl = useIntl()
  const breakfastData = useAddAncillaryStore((state) => state.breakfastData)

  if (!breakfastData) {
    return intl.formatMessage({
      defaultMessage: "Unable to display breakfast prices.",
    })
  }

  return (
    <div className={styles.breakfastContainer}>
      <Alert
        type={AlertTypeEnum.Info}
        text={intl.formatMessage({
          defaultMessage:
            "Breakfast can only be added for the entire duration of the stay and for all guests.",
        })}
      />
      {(breakfastData.nrOfPayingChildren > 0 ||
        breakfastData.nrOfFreeChildren > 0) && (
        <dl className={styles.breakfastPrices}>
          <div className={styles.breakfastPriceBox}>
            <MaterialIcon icon="check_circle" className={styles.icon} />
            <div>
              <dt>
                {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                {`${breakfastData.nrOfAdults} × ${intl.formatMessage({
                  defaultMessage: "Adults",
                })}`}
              </dt>
              <dd>
                <Body>
                  {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                  {`${breakfastData.priceAdult * breakfastData.nrOfAdults} ${breakfastData.currency}`}
                </Body>
              </dd>
            </div>
          </div>

          {breakfastData.nrOfPayingChildren > 0 && (
            <div className={styles.breakfastPriceBox}>
              <MaterialIcon icon="check_circle" className={styles.icon} />
              <div>
                <dt>
                  {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                  {`${breakfastData.nrOfPayingChildren} × ${intl.formatMessage({
                    defaultMessage: "ages",
                  })} 4-12`}
                </dt>
                <dd>
                  <Body>
                    {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                    {`${breakfastData.priceChild * breakfastData.nrOfPayingChildren} ${breakfastData.currency}`}
                  </Body>
                </dd>
              </div>
            </div>
          )}

          {breakfastData.nrOfFreeChildren > 0 && (
            <div className={`${styles.breakfastPriceBox} ${styles.free}`}>
              <MaterialIcon icon="check_circle" className={styles.icon} />
              <div>
                <dt>
                  {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
                  {`${breakfastData.nrOfFreeChildren} × ${intl.formatMessage({
                    defaultMessage: "under",
                  })} 4`}
                </dt>
                <dd>
                  <Body>
                    {intl.formatMessage({
                      defaultMessage: "Free",
                    })}
                  </Body>
                </dd>
              </div>
            </div>
          )}
        </dl>
      )}
    </div>
  )
}
