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 SectionWrapper from "../SectionWrapper"

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

import type { 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 intl = await getIntl()

  let pointsMsg: React.ReactNode = intl.formatMessage(
    { id: "{pointsAmount, number} points" },
    { pointsAmount: level.required_points }
  )

  if (level.required_nights) {
    pointsMsg = intl.formatMessage<React.ReactNode>(
      {
        id: "{pointsAmount, number} points <highlight>or {nightsAmount, number} nights</highlight>",
      },
      {
        pointsAmount: level.required_points,
        nightsAmount: level.required_nights,
        highlight: (str) => <span className={styles.redText}>{str}</span>,
      }
    )
  }

  return (
    <article className={styles.card}>
      <header>
        <BiroScript
          type="two"
          color="primaryLightOnSurfaceAccent"
          tilted="large"
        >
          {intl.formatMessage(
            { id: "Level {level}" },
            { level: level.user_facing_tag }
          )}
        </BiroScript>
        <MembershipLevelIcon level={level.level_id} color="red" />
      </header>
      <Title textAlign="center" level="h5">
        {pointsMsg}
      </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>
  )
}
