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

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

import MembershipLevelIcon from "@/components/Levels/Icon"
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,
}: LoyaltyLevelsProps) {
  const caller = await serverClient()
  const uniqueLevels = await caller.contentstack.rewards.all({
    unique: true,
  })

  return (
    <SectionWrapper dynamic_content={dynamic_content}>
      <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: "common.pointsAmountPoints",
      defaultMessage: "{pointsAmount, number} points",
    },
    { pointsAmount: level.required_points }
  )

  if (level.required_nights) {
    pointsMsg = intl.formatMessage(
      {
        id: "loyaltyLevelsBlock.pointsOrNights",
        defaultMessage:
          "{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>
        <Typography variant="Title/Decorative/md">
          <p className={styles.scriptedText}>
            {intl.formatMessage(
              {
                id: "common.membershipLevelWithValue",
                defaultMessage: "Level {level}",
              },
              { level: level.user_facing_tag }
            )}
          </p>
        </Typography>
        <MembershipLevelIcon level={level.level_id} color="red" />
      </header>
      <Typography variant="Title/xs" className={styles.pointMsg}>
        <h5>{pointsMsg}</h5>
      </Typography>
      <Typography variant="Body/Supporting text (caption)/smRegular">
        <div className={styles.textContainer}>
          {level.rewards.map((reward) => (
            <p className={styles.levelText} key={reward.reward_id}>
              <MaterialIcon
                icon="check"
                className={styles.checkIcon}
                color="Icon/Interactive/Accent"
              />
              {reward.label}
            </p>
          ))}
        </div>
      </Typography>
    </article>
  )
}
