package com.seven.ikar.kotlin.feature.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class LoginUiState(
    val email: String = "",
    val phoneNumber: String = "",
    val displayName: String = "",
    val verificationCode: String = "",
    val challengeId: String = "",
    val isAwaitingCode: Boolean = false,
    val isNewAccount: Boolean = false,
    val isLoading: Boolean = false,
    val errorMessage: String? = null,
    val isAuthenticated: Boolean = false
) {
    val pageTitle: String
        get() = if (isAwaitingCode) "Подтвердите email" else "Вход в ИКАР"

    val subtitle: String
        get() = if (isAwaitingCode) {
            "Введите код, который отправлен на указанную электронную почту."
        } else {
            "Введите электронную почту и номер телефона. Код придёт только на email."
        }

    val showEmailStep: Boolean
        get() = !isAwaitingCode

    val showCodeStep: Boolean
        get() = isAwaitingCode

    val showDisplayName: Boolean
        get() = isAwaitingCode && isNewAccount
}

class LoginViewModel(private val container: AppContainer) : ViewModel() {
    private val _uiState = MutableStateFlow(LoginUiState())
    val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()

    fun updateEmail(value: String) {
        _uiState.value = _uiState.value.copy(email = value, errorMessage = null)
    }

    fun updatePhoneNumber(value: String) {
        _uiState.value = _uiState.value.copy(phoneNumber = value, errorMessage = null)
    }

    fun updateDisplayName(value: String) {
        _uiState.value = _uiState.value.copy(displayName = value, errorMessage = null)
    }

    fun updateVerificationCode(value: String) {
        _uiState.value = _uiState.value.copy(verificationCode = value, errorMessage = null)
    }

    fun requestCode() {
        val state = _uiState.value
        if (state.isLoading) {
            return
        }

        if (state.email.isBlank() || state.phoneNumber.isBlank()) {
            _uiState.value = state.copy(errorMessage = "Введите email и номер телефона.")
            return
        }

        viewModelScope.launch(Dispatchers.IO) {
            _uiState.value = state.copy(isLoading = true, errorMessage = null)
            runCatching {
                container.apiClient.requestEmailCode(
                    email = state.email.trim(),
                    phoneNumber = state.phoneNumber.trim()
                )
            }.onSuccess { challenge ->
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    challengeId = challenge.challengeId,
                    isAwaitingCode = true,
                    isNewAccount = !challenge.isRegistered,
                    verificationCode = "",
                    errorMessage = null
                )
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    errorMessage = error.message ?: "Не удалось отправить код на email."
                )
            }
        }
    }

    fun verifyCode() {
        val state = _uiState.value
        if (state.isLoading ||
            state.challengeId.isBlank() ||
            state.email.isBlank() ||
            state.phoneNumber.isBlank() ||
            state.verificationCode.isBlank() ||
            (state.isNewAccount && state.displayName.isBlank())
        ) {
            return
        }

        viewModelScope.launch(Dispatchers.IO) {
            _uiState.value = state.copy(isLoading = true, errorMessage = null)
            runCatching {
                container.apiClient.verifyEmailCode(
                    challengeId = state.challengeId,
                    email = state.email.trim(),
                    phoneNumber = state.phoneNumber.trim(),
                    code = state.verificationCode.trim(),
                    displayName = state.displayName.trim().ifBlank { null }
                )
            }.onSuccess { session ->
                container.sessionStore.save(session)
                runCatching { container.pushRegistrationManager.registerCurrentDeviceAsync() }
                _uiState.value = _uiState.value.copy(isLoading = false, isAuthenticated = true)
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    errorMessage = error.message ?: "Не удалось подтвердить email-код."
                )
            }
        }
    }

    fun changeEmail() {
        _uiState.value = _uiState.value.copy(
            challengeId = "",
            verificationCode = "",
            isAwaitingCode = false,
            isNewAccount = false,
            errorMessage = null
        )
    }
}
