import { redirect } from "next/navigation"
import React from "react"
import { z } from "zod"

import { Typography } from "@scandic-hotels/design-system/Typography"

import { env } from "@/env/server"

import Image from "@/components/Image"
import { Redirect } from "@/components/Redirect"
import Link from "@/components/TempDesignSystem/Link"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import { getIntl } from "@/i18n"

import { SASModal } from "../components/SASModal"

import type { LangParams, PageArgs, SearchParams } from "@/types/params"
import type { Lang } from "@/constants/languages"
import type { State } from "../sasUtils"

const searchParamsSchema = z.object({
  intent: z.enum(["link", "unlink", "transfer"]),
})

type Intent = z.infer<typeof searchParamsSchema>["intent"]

export default async function SASxScandicLoginPage(props: PageArgs<LangParams> & SearchParams) {
  const params = await props.params;
  const searchParams = await props.searchParams;
  const result = searchParamsSchema.safeParse(searchParams)
  if (!result.success) {
    // TOOD where to redirect?
    redirect(`/${params.lang}/sas-x-scandic/link`)
  }
  const parsedParams = result.data

  const intl = await getIntl()
  const redirectUri = new URL(
    `/${params.lang}/sas-x-scandic/callback`,
    env.PUBLIC_URL
  ).toString()

  const state: State = { intent: parsedParams.intent }
  const urlState = encodeURIComponent(JSON.stringify(state))
  const clientId = env.SAS_AUTH_CLIENTID
  const sasLoginHostname = env.SAS_AUTH_ENDPOINT
  const audience = "eb-partner-api"
  const scope = encodeURIComponent("openid profile email")

  const loginLink = `${sasLoginHostname}/oauth/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&state=${urlState}&audience=${audience}&ui_locales=${SAS_LANGUAGE_MAP[params.lang]}`

  const intentDescriptions: Record<Intent, string> = {
    link: intl.formatMessage({
      defaultMessage:
        "Log in to your SAS EuroBonus account to confirm account linking.",
    }),
    unlink: intl.formatMessage({
      defaultMessage:
        "Log in to your SAS Eurobonus account to confirm account unlinking.",
    }),
    transfer: intl.formatMessage({
      defaultMessage:
        "In order to transfer your points we will ask you to sign in to your SAS EuroBonus account.",
    }),
  }

  return (
    <SASModal>
      <Redirect url={loginLink} timeout={3000} />
      <Image
        src="/_static/img/scandic-loyalty-time.svg"
        alt=""
        width="140"
        height="110"
        style={{ marginTop: 16 }}
      />
      <Typography variant="Title/Subtitle/lg">
        <h1>
          {intl.formatMessage({
            defaultMessage: "Redirecting you to SAS",
          })}
        </h1>
      </Typography>
      <Typography variant="Body/Paragraph/mdRegular">
        <p style={{ textAlign: "center" }}>
          {intentDescriptions[parsedParams.intent]}
        </p>
      </Typography>
      <Footnote textAlign="center">
        {intl.formatMessage(
          {
            defaultMessage:
              "If you are not redirected automatically, please <loginLink>click here</loginLink>.",
          },
          {
            loginLink: (str) => (
              <Link
                href={loginLink}
                color="red"
                size="tiny"
                textDecoration="underline"
              >
                {str}
              </Link>
            ),
          }
        )}
      </Footnote>
    </SASModal>
  )
}

const SAS_LANGUAGE_MAP: Record<Lang, string> = {
  no: "nb",
  sv: "sv",
  fi: "fi",
  da: "da",
  en: "en",
  de: "de",
}
