import { dt } from "@scandic-hotels/common/dt"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { getScandicNativeMembership } from "@scandic-hotels/trpc/routers/user/helpers"

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

import ProgressCardHighestLevel from "./InnerCard/ProgressCardHighestLevel"
import ProgressCardLowerLevel from "./InnerCard/ProgressCardLowerLevel"
import SuccessCard from "./InnerCard/SuccessCard"
import LevelProgressModal from "./LevelProgressModal"
import { getLevelProgressData } from "./utils"
import { levelProgressCardVariants } from "./variants"

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

import type { levelProgressCardProps } from "./types"

export default async function LevelProgressCard({
  user,
  className,
  color = "Surface/Brand/Primary 1/OnSurface/Default",
}: levelProgressCardProps) {
  const friendsMembership = user.loyalty
    ? getScandicNativeMembership(user.loyalty)
    : null

  if (!friendsMembership) {
    return null
  }

  const intl = await getIntl()
  const lang = await getLang()
  const data = await getLevelProgressData(friendsMembership)
  const classNames = levelProgressCardVariants({ className, color })

  return (
    <section aria-labelledby="level-progress-card-title" className={classNames}>
      <header className={styles.progressHeader}>
        <Typography variant="Title/xs">
          <h2 id="level-progress-card-title" className={styles.title}>
            {intl.formatMessage({
              defaultMessage: "Your Level Progress",
            })}
          </h2>
        </Typography>
        <Typography variant="Body/Paragraph/mdRegular">
          <p className={styles.date}>
            {intl.formatMessage(
              { defaultMessage: "Valid until {date}" },
              {
                date: dt(friendsMembership.tierExpires)
                  .locale(lang)
                  .format("D MMM YYYY"),
              }
            )}
          </p>
        </Typography>
        <LevelProgressModal
          color={color}
          tierExpires={friendsMembership.tierExpires}
        />
      </header>

      {data.type === "highest-complete" && (
        <SuccessCard pointsEarned={data.earned} />
      )}

      {data.type === "highest-incomplete" && (
        <ProgressCardHighestLevel
          earned={data.earned}
          required={data.required}
          toKeepCurrent={data.toKeepCurrent}
        />
      )}

      {data.type === "lower-level" && (
        <ProgressCardLowerLevel
          earned={data.earned}
          toNext={data.toNext}
          toKeepCurrent={data.toKeepCurrent}
        />
      )}
    </section>
  )
}
