import { Suspense } from "react"

import { TIER_TO_FRIEND_MAP } from "@/constants/membershipLevels"
import { env } from "@/env/server"
import { getProfile } from "@/lib/trpc/memoizedRequests"

import SectionContainer from "@/components/Section/Container"
import SectionHeader from "@/components/Section/Header"
import SectionLink from "@/components/Section/Link"
import { timeout } from "@/utils/timeout"

import { TierLevelCard, TierLevelCardSkeleton } from "./Card/TierLevelCard"
import { LevelUpgradeButton } from "./LevelUpgradeButton"
import { UnlinkSAS } from "./UnlinkSAS"

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

type Props = {
  title?: string
  link?: { href: string; text: string }
  subtitle?: string
}

export default async function SASLinkedAccount({
  title,
  subtitle,
  link,
}: Props) {
  if (!env.SAS_ENABLED) {
    return null
  }

  return (
    <>
      <SectionContainer>
        <SectionHeader link={link} preamble={subtitle} title={title} />
        <SectionLink link={link} variant="mobile" />
        <section className={styles.cardsContainer}>
          <Suspense fallback={<TierLevelCardsSkeleton />}>
            <TierLevelCards />
          </Suspense>
        </section>
      </SectionContainer>
      <div className={styles.mutationSection}>
        <UnlinkSAS />
        <LevelUpgradeButton />
      </div>
    </>
  )
}

function TierLevelCardsSkeleton() {
  return (
    <>
      <TierLevelCardSkeleton bonusSystem={"scandic"} />
      <TierLevelCardSkeleton bonusSystem={"sas"} />
    </>
  )
}

async function TierLevelCards() {
  console.log("[SAS] Fetching tier level cards")
  await timeout(2_000)
  console.log("[SAS] AFTER Fetching tier level cards")

  const user = await getProfile()
  if (!user || "error" in user) {
    return null
  }

  const sasPoints = 250_000
  const sfPoints = user.membership?.currentPoints || 0
  const sfLevelName =
    TIER_TO_FRIEND_MAP[user.membership?.membershipLevel ?? "L1"]

  return (
    <>
      <TierLevelCard
        points={sfPoints}
        tier={sfLevelName}
        boostState="boostedInThisSystem"
        bonusSystem={"scandic"}
      />
      <TierLevelCard
        points={sasPoints}
        tier="Silver"
        boostState="boostedInOtherSystem"
        bonusSystem={"sas"}
        boostExpiration={new Date("2022-12-31")}
        boostedTier="Gold"
      />
    </>
  )
}
