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

import { getProfile } from "@/lib/trpc/memoizedRequests"

import AccountPage from "@/components/Webviews/AccountPage"
import LoyaltyPage from "@/components/Webviews/LoyaltyPage"
import { getIntl } from "@/i18n"

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

export default async function ContentTypePage(
  props: PageArgs<LangParams & ContentTypeWebviewParams & UIDParams, {}>
) {
  const params = await props.params
  const intl = await getIntl()
  const user = await getProfile()

  if (!user) {
    console.log(`[webview:page] unable to load user`)
    return (
      <p>
        {intl.formatMessage({
          defaultMessage: "Error: No user could be loaded",
        })}
      </p>
    )
  }

  if ("error" in user) {
    switch (user.cause) {
      case "unauthorized": // fall through
      case "forbidden": // fall through
      case "token_expired":
        const headersList = await headers()
        const returnURL = `/${params.lang}/webview${headersList.get("x-pathname")!}`
        const redirectURL = `/${params.lang}/webview/refresh?returnUrl=${encodeURIComponent(returnURL)}`
        console.log(`[webview:page] user error, redirecting to: ${redirectURL}`)
        redirect(redirectURL)
      case "notfound":
        return (
          <p>
            {intl.formatMessage({
              defaultMessage: "Error: user not found",
            })}
          </p>
        )
      case "unknown":
        return (
          <p>
            {intl.formatMessage({
              defaultMessage: "Unknown error occurred loading user",
            })}
          </p>
        )
      default:
        const u: never = user
        console.log("[webview:page] unhandled user loading error", u)
    }
  }

  switch (params.contentType) {
    case "loyalty-page":
      return <LoyaltyPage />
    case "account-page":
      return <AccountPage />
    default:
      const type: never = params.contentType
      console.error(`Unsupported content type given: ${type}`)
      notFound()
  }
}
