import { serverClient } from "@/lib/trpc/server"

import { CheckIcon } from "@/components/Icons"
import MembershipLevelIcon from "@/components/Levels/Icon"
import BiroScript from "@/components/TempDesignSystem/Text/BiroScript"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Title from "@/components/TempDesignSystem/Text/Title"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"

import SectionWrapper from "../SectionWrapper"

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

import { LoyaltyLevelsProps } from "@/types/components/blocks/dynamicContent"
import type { LevelCardProps } from "@/types/components/overviewTable"

export default async function LoyaltyLevels({
  dynamic_content,
  firstItem,
}: LoyaltyLevelsProps) {
  const uniqueLevels = await serverClient().contentstack.rewards.all({
    unique: true,
  })

  return (
    <SectionWrapper dynamic_content={dynamic_content} firstItem={firstItem}>
      <section className={styles.cardContainer}>
        {uniqueLevels.map((level) => (
          <LevelCard key={level.level_id} level={level} />
        ))}
      </section>
    </SectionWrapper>
  )
}

async function LevelCard({ level }: LevelCardProps) {
  const lang = getLang()
  const intl = await getIntl()
  const pointsString = `${level.required_points.toLocaleString(lang)} ${intl.formatMessage({ id: "points" })} `

  return (
    <article className={styles.card}>
      <header>
        <BiroScript
          type="two"
          color="primaryLightOnSurfaceAccent"
          tilted="large"
        >
          {intl.formatMessage({ id: "Level" })} {level.user_facing_tag}
        </BiroScript>
        <MembershipLevelIcon level={level.level_id} color="red" />
      </header>
      <Title textAlign="center" level="h5">
        {pointsString}
        {level.required_nights ? (
          <span className={styles.redText}>
            {intl.formatMessage({ id: "or" })} {level.required_nights}{" "}
            {intl.formatMessage({ id: "nights" })}
          </span>
        ) : null}
      </Title>
      <div className={styles.textContainer}>
        {level.rewards.map((reward) => (
          <Caption
            className={styles.levelText}
            key={reward.reward_id}
            textAlign="center"
            color="textMediumContrast"
          >
            <CheckIcon
              className={styles.checkIcon}
              color="primaryLightOnSurfaceAccent"
            />
            {reward.label}
          </Caption>
        ))}
      </div>
    </article>
  )
}
