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

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

import MembershipLevelIcon from "@/components/Levels/Icon"
import BiroScript from "@/components/TempDesignSystem/Text/BiroScript"
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>
        <BiroScript
          type="two"
          color="primaryLightOnSurfaceAccent"
          tilted="large"
        >
          {intl.formatMessage(
            {
              id: "common.membershipLevelWithValue",
              defaultMessage: "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"
          >
            <MaterialIcon
              icon="check"
              className={styles.checkIcon}
              color="Icon/Interactive/Accent"
            />
            {reward.label}
          </Caption>
        ))}
      </div>
    </article>
  )
}
