import { redirect } from "next/navigation"
import { auth0 } from "@/lib/auth0"
import Link from "next/link"
import { Suspense, type JSX } from "react"
import { APP_ROUTES } from "@/lib/types"

// Security function to validate returnTo URLs
function isValidReturnUrl(url: string): boolean {
  if (url.startsWith("/")) {
    return true
  }
  return false
}

async function LoginContent(props: {
  searchParams: Promise<{ returnTo?: string; error?: string }>
}): Promise<JSX.Element> {
  const searchParams = await props.searchParams
  const session = await auth0.getSession()

  if (session) {
    // User is already logged in
    console.log(`[Login] User ${session.user.sub} already authenticated`)
    const returnTo =
      searchParams.returnTo && isValidReturnUrl(searchParams.returnTo) ? searchParams.returnTo : "/"
    redirect(returnTo)
  }

  // Show error if there was one
  if (searchParams.error) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold">Login Error</h2>
          <p className="mt-2">There was an error during login. Please try again.</p>
          <Link
            href="/auth/login"
            className="mt-4 inline-block rounded bg-blue-500 px-4 py-2 text-white"
          >
            Try Again
          </Link>
        </div>
      </div>
    )
  }

  // Not logged in - redirect to Auth0
  const returnTo =
    searchParams.returnTo && isValidReturnUrl(searchParams.returnTo)
      ? searchParams.returnTo
      : APP_ROUTES.BASE

  console.log(`[Login Page] Redirecting to Auth0 with returnTo: ${returnTo}`)
  const loginUrl = `/auth/login?returnTo=${encodeURIComponent(returnTo)}`
  redirect(loginUrl)
}

export default function AuthenticationPage(props: {
  searchParams: Promise<{ returnTo?: string; error?: string }>
}): JSX.Element {
  return (
    <Suspense
      fallback={
        <div className="flex min-h-screen items-center justify-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-blue-500" />
        </div>
      }
    >
      <LoginContent searchParams={props.searchParams} />
    </Suspense>
  )
}
