package dev.zxq5.chatapp.android.feature.auth

import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import dev.zxq5.chatapp.android.api.model.LoginState

@Composable
fun AuthScreen(viewModel: AuthViewModel) {
    val loginState by viewModel.loginState.collectAsState()
    val authMode by viewModel.authMode.collectAsState()
    val totpError by viewModel.totpError.collectAsState()

    if (loginState is LoginState.TwoFactorRequired ||
        (loginState is LoginState.Loading && totpError != null)) {
        TwoFactorLoginScreen(
            onVerify = { viewModel.verifyTotpLogin(it) },
            onBack = {
                viewModel.clearTotpError()
                viewModel.setAuthMode(AuthMode.LOGIN)
            },
            isLoading = loginState is LoginState.Loading,
            error = totpError
        )
        return
    }

    if (authMode == AuthMode.SIGNUP) {
        SignupScreen(
            viewModel = viewModel,
            onSwitchToLogin = { viewModel.setAuthMode(AuthMode.LOGIN) }
        )
    } else {
        LoginScreen(
            viewModel = viewModel,
            onSwitchToSignup = { viewModel.setAuthMode(AuthMode.SIGNUP) }
        )
    }
}