import { MembershipLevelEnum } from "@scandic-hotels/common/constants/membershipLevels"
import { dt } from "@scandic-hotels/common/dt"
import { Typography } from "@scandic-hotels/design-system/Typography"

import { TIER_TO_FRIEND_MAP } from "@/constants/membershipLevels"
import { getProfile } from "@/lib/trpc/memoizedRequests"

import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
import { getTierStartDate } from "@/utils/getTierStartDate"

import { L6ProgressModal } from "./L6ProgressModal"
import { ProgressSection } from "./ProgressSection"

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

const MAX_NIGHTS = 100

export async function L6Progress() {
  const user = await getProfile()
  const intl = await getIntl()
  const lang = await getLang()

  if (
    !user ||
    "error" in user ||
    user?.membership?.membershipLevel !== MembershipLevelEnum.L6
  ) {
    return null
  }

  const nightsToTopTier = user?.membership?.nightsToTopTier

  // A simple falsy check won't work here as we want to pass through 0.
  if (nightsToTopTier === null || nightsToTopTier === undefined) {
    return null
  }

  const nightsStayed = MAX_NIGHTS - nightsToTopTier
  // Cap progress at 100 to prevent overflow.
  const progressValue = Math.min(nightsStayed, MAX_NIGHTS)

  const tierStartDate = getTierStartDate(user.membership.tierExpirationDate)
  const formattedStartDate = tierStartDate
    ? dt(tierStartDate).locale(lang).format("D MMMM YYYY")
    : null

  const bestFriendLabel = TIER_TO_FRIEND_MAP[MembershipLevelEnum.L7]

  return (
    <div className={styles.l6Progress}>
      <header className={styles.header}>
        <Typography variant="Title/Subtitle/md">
          <h3 className={styles.title}>
            {intl.formatMessage({
              id: "previousStays.totalStays",
              defaultMessage: "Total stays",
            })}
          </h3>
        </Typography>
        {formattedStartDate && (
          <>
            <Typography variant="Body/Paragraph/mdRegular">
              <span className={styles.sinceDate}>
                <p className={styles.since}>
                  {intl.formatMessage(
                    {
                      id: "previousStays.sinceDate",
                      defaultMessage: "Since {date}",
                    },
                    { date: formattedStartDate }
                  )}
                </p>
                <L6ProgressModal
                  tierExpires={user.membership.tierExpirationDate}
                />
              </span>
            </Typography>
          </>
        )}
      </header>

      <ProgressSection
        nightsStayed={nightsStayed}
        progressValue={progressValue}
        maxNights={MAX_NIGHTS}
        bestFriendLabel={bestFriendLabel}
      />
    </div>
  )
}
