import "@/app/globals.css"
import "@scandic-hotels/design-system/style.css"

import { notFound, redirect } from "next/navigation"

import { Lang } from "@/constants/languages"
import { overview } from "@/constants/routes/webviews"
import { _ } from "@/lib/translation"
import { serverClient } from "@/lib/trpc/server"

import MaxWidth from "@/components/MaxWidth"
import Content from "@/components/MyPages/AccountPage/Webview/Content"

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

import type { LangParams, PageArgs, UriParams } from "@/types/params"

function getLink(lang: Lang, uri: string) {
  if (uri === overview[lang]) {
    return {
      title: _("Go to points"),
      href: `/${lang}/webview/my-pages/points`,
    }
  } else {
    return {
      title: _("Go to membership overview"),
      href: `/${lang}/webview/my-pages/overview`,
    }
  }
}

export default async function MyPages({
  params,
  searchParams,
}: PageArgs<LangParams, UriParams>) {
  if (!searchParams.uri) {
    return notFound()
  }

  // Check if the access token is valid. If not, redirect to the refresh page.
  await serverClient({
    onError(opts) {
      const returnUrl = new URLSearchParams({
        returnurl: `${params.lang}/webview/${searchParams.uri}`,
      })

      const refreshUrl = `/${params.lang}/webview/refresh?${returnUrl.toString()}`
      redirect(refreshUrl)
    },
  }).user.get()

  const accountPage = await serverClient({
    onError() {
      const returnUrl = new URLSearchParams({
        returnurl: `${params.lang}/webview/${searchParams.uri}`,
      })

      const refreshUrl = `/${params.lang}/webview/refresh?${returnUrl.toString()}`
      redirect(refreshUrl)
    },
  }).contentstack.accountPage.get({
    url: searchParams.uri,
    lang: params.lang,
  })

  const link = getLink(params.lang, searchParams.uri)

  return (
    <MaxWidth className={styles.blocks} tag="main">
      <Content lang={params.lang} content={accountPage.content} />
    </MaxWidth>
  )
}
