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

import SectionContainer from "@/components/Section/Container"
import SectionHeader from "@/components/Section/Header"
import SectionLink from "@/components/Section/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/content/blocks"
import { DynamicContentComponentEnum } from "@/types/components/content/enums"

async function DynamicComponentBlock({ component }: DynamicComponentProps) {
  const membershipLevel = await serverClient().user.membershipLevel()
  switch (component) {
    case DynamicContentComponentEnum.how_it_works:
      return <HowItWorks />
    case DynamicContentComponentEnum.loyalty_levels:
      return <LoyaltyLevels />
    case DynamicContentComponentEnum.overview_table:
      return <OverviewTable activeMembership={membershipLevel} />
    default:
      return null
  }
}

export default function DynamicContent({
  dynamicContent,
  firstItem,
}: DynamicContentProps) {
  const displayHeader = !!(
    dynamicContent.link ||
    dynamicContent.subtitle ||
    dynamicContent.title
  )
  const isOverviewTable =
    dynamicContent.component === DynamicContentComponentEnum.overview_table
  return (
    <SectionContainer className={styles.container}>
      {isOverviewTable ? (
        <div className={styles.header}>
          <Title className={styles.tableTitle}> {dynamicContent.title}</Title>
          <Subtitle>{dynamicContent.subtitle}</Subtitle>
        </div>
      ) : displayHeader ? (
        <SectionHeader
          link={dynamicContent.link}
          preamble={dynamicContent.subtitle}
          title={dynamicContent.title}
          topTitle={firstItem}
        />
      ) : null}
      <DynamicComponentBlock component={dynamicContent.component} />
      {displayHeader && (
        <SectionLink link={dynamicContent.link} variant="mobile" />
      )}
    </SectionContainer>
  )
}
