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

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

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

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

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

const searchParamsSchema = z.object({
  intent: z.enum(["link"]),
})
export default async function SASxScandicLoginPage({
  searchParams,
  params,
}: PageArgs<LangParams> & 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(
    "/en/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"
  // TODO check if this is correct scopes
  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}`

  return (
    <SASModal>
      <Redirect url={loginLink} timeout={3000} />
      <Image
        src="/_static/img/scandic-loyalty-time.svg"
        alt=""
        width="140"
        height="110"
        style={{ marginTop: 16 }}
      />
      <Title as="h2" level="h1" textTransform="regular">
        {intl.formatMessage({ id: "Redirecting you to SAS" })}
      </Title>
      <Body textAlign="center">
        {intl.formatMessage({
          id: "In order to verify your account linking we will ask you to sign in to your SAS EuroBonus account.",
        })}
      </Body>
      <Footnote textAlign="center">
        {intl.formatMessage<React.ReactNode>(
          {
            id: "If you are not redirected automatically, please <loginLink>click here</loginLink>.",
          },
          {
            loginLink: (str) => (
              <Link
                href={loginLink}
                color="red"
                variant="default"
                size="tiny"
                textDecoration="underline"
              >
                {str}
              </Link>
            ),
          }
        )}
      </Footnote>
    </SASModal>
  )
}
