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

import { auth } from "@/auth"
import Link from "@/components/TempDesignSystem/Link"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import Title from "@/components/TempDesignSystem/Text/Title"

import HowItWorks from "./HowItWorks"
import LoyaltyLevels from "./LoyaltyLevels"
import OverviewTable from "./OverviewTable"

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

import type {
  DynamicComponentProps,
  DynamicContentProps,
} from "@/types/components/loyalty/blocks"
import { LoyaltyComponentEnum } from "@/types/components/loyalty/enums"

async function DynamicComponentBlock({ component }: DynamicComponentProps) {
  const session = await auth()

  const user = session ? await serverClient().user.get() : null

  switch (component) {
    case LoyaltyComponentEnum.how_it_works:
      return <HowItWorks />
    case LoyaltyComponentEnum.loyalty_levels:
      return <LoyaltyLevels />
    case LoyaltyComponentEnum.overview_table:
      return <OverviewTable user={user} />
    default:
      return null
  }
}

export default function DynamicContent({
  dynamicContent,
}: DynamicContentProps) {
  const displayHeader = !!(
    dynamicContent.title ||
    dynamicContent.subtitle ||
    dynamicContent.title
  )

  return (
    <section className={styles.container}>
      {displayHeader ? (
        <header className={styles.titleContainer}>
          <Title as="h3" className={styles.title} level="h2">
            {dynamicContent.title}
          </Title>
          {dynamicContent.link ? (
            <Link className={styles.link} href={dynamicContent.link.href}>
              {dynamicContent.link.text}
            </Link>
          ) : null}
          <Subtitle className={styles.subtitle}>
            {dynamicContent.subtitle}
          </Subtitle>
        </header>
      ) : null}
      <DynamicComponentBlock component={dynamicContent.component} />
    </section>
  )
}
