'use client'

import { useAuthContext, useConfig } from '../../contexts/AuthContext'
import { getAuthDetails } from '../../api'
import { AuthDjangoForm } from '../AuthDjangoForm'
import { PasskeyLogin } from '../PasskeyLogin'
import { ProviderList } from '../ProviderList'
import type { AllauthConfiguration } from '../../types'

interface LoginViewProps {
    /** Called after successful login (or when MFA is triggered) */
    onSuccess?: () => void
    /** Called when user clicks "Create account" */
    onSignupClick?: () => void
    /** Called when user clicks "Forgot password" */
    onForgotPasswordClick?: () => void
    /** Called when user clicks "Sign in with code" */
    onLoginByCodeClick?: () => void
    /** OAuth callback URL for social providers */
    oauthCallbackUrl?: string
}

export function LoginView({
    onSuccess,
    onSignupClick,
    onForgotPasswordClick,
    onLoginByCodeClick,
    oauthCallbackUrl,
}: LoginViewProps) {
    const { refresh } = useAuthContext()
    const config = useConfig()

    // Get feature flags from backend config
    const allauthConfig = config?.data as AllauthConfiguration | undefined
    const isSignupEnabled = allauthConfig?.account?.is_open_for_signup ?? true
    const isLoginByCodeEnabled = allauthConfig?.account?.login_by_code_enabled ?? false

    const handleSuccess = async () => {
        const newAuth = await refresh()
        const details = getAuthDetails(newAuth)

        // Only call onSuccess if fully authenticated (no pending MFA)
        // If MFA is pending, AllauthUI will handle showing the MFA view
        if (details.isAuthenticated) {
            onSuccess?.()
        }
    }

    // Build footer links based on provided callbacks AND backend config
    const footerLinks: Array<{ href?: string; label: string; onClick?: () => void }> = []

    if (onForgotPasswordClick) {
        footerLinks.push({ label: 'Forgot your password?', onClick: onForgotPasswordClick })
    }
    if (onLoginByCodeClick && isLoginByCodeEnabled) {
        footerLinks.push({ label: 'Sign in with a code instead', onClick: onLoginByCodeClick })
    }
    if (onSignupClick && isSignupEnabled) {
        footerLinks.push({ label: "Don't have an account? Sign up", onClick: onSignupClick })
    }

    return (
        <AuthDjangoForm
            formName="login"
            onSuccess={handleSuccess}
            footerLinks={footerLinks}
            postFields={
                <>
                    <PasskeyLogin onSuccess={onSuccess} />
                    {oauthCallbackUrl && <ProviderList callbackUrl={oauthCallbackUrl} />}
                </>
            }
        />
    )
}
