'use client'

import { useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { handleSSOCallback, getPortalForRole } from '@/lib/auth/sso'

export default function SSOCallbackPage() {
  const router = useRouter()
  const searchParams = useSearchParams()

  useEffect(() => {
    const code = searchParams?.get('code')
    const state = searchParams?.get('state')

    if (code && state) {
      const keycloakUrl = process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'https://keycloak.sankofa.nexus'
      const realm = process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'sankofa'
      const clientId = process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID || 'phoenix-portal'
      const redirectUri = `${window.location.origin}/portal/callback`

      handleSSOCallback(code, state, {
        keycloakUrl,
        realm,
        clientId,
        redirectUri,
      })
        .then(({ token, user, role }) => {
          // Store token
          if (typeof window !== 'undefined') {
            sessionStorage.setItem('auth_token', token)
            localStorage.setItem('phoenix_token', token)
            localStorage.setItem('phoenix_user', JSON.stringify(user))
          }

          // Route to appropriate portal
          const portal = getPortalForRole(role)
          router.push(portal)
        })
        .catch((error) => {
          console.error('SSO callback error:', error)
          router.push('/portal/signin?error=sso_failed')
        })
    } else {
      // No code/state, redirect to sign in
      router.push('/portal/signin')
    }
  }, [searchParams, router])

  return (
    <div className="flex min-h-screen items-center justify-center bg-studio-black">
      <div className="text-center">
        <div className="mb-4 inline-block h-8 w-8 animate-spin rounded-full border-4 border-phoenix-fire border-t-transparent" />
        <p className="text-gray-400">Completing sign in...</p>
      </div>
    </div>
  )
}

