import { useEffect } from 'react'
import { createPKCE, storePKCE, storeState } from '../auth/oidc'

const OIDC_ISSUER = import.meta.env.VITE_OIDC_ISSUER
const CLIENT_ID = import.meta.env.VITE_OIDC_CLIENT_ID
const REDIRECT_URI = import.meta.env.VITE_OIDC_REDIRECT_URI

function generateState(): string {
  const array = new Uint8Array(32)
  crypto.getRandomValues(array)
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('')
}

export default function LoginPage() {
  useEffect(() => {
    const initiateLogin = async () => {
      const { verifier, challenge } = await createPKCE()
      storePKCE(verifier)

      const state = generateState()
      storeState(state)

      const params = new URLSearchParams({
        client_id: CLIENT_ID,
        redirect_uri: REDIRECT_URI,
        response_type: 'code',
        scope: 'openid profile email',
        code_challenge: challenge,
        code_challenge_method: 'S256',
        state,
      })

      const authorizationEndpoint = 'https://auth.commumedia.org/application/o/authorize/'
      window.location.href = `${authorizationEndpoint}?${params.toString()}`
    }

    initiateLogin()
  }, [])

  return (
    <div className="flex min-h-screen items-center justify-center">
      <div className="text-center">
        <h1 className="text-2xl font-bold mb-4">Redirecting to login...</h1>
        <p className="text-gray-400">Please wait while we redirect you to the authentication provider.</p>
      </div>
    </div>
  )
}
