package com.devlab.app.ui.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.devlab.app.ServerManagerApp
import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.repository.AuthRepository
import com.devlab.app.util.PreferencesManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class LoginUiState(
    val username: String = "",
    val password: String = "",
    val isLoading: Boolean = false,
    val error: String? = null,
    val isConnected: Boolean = false
)

class LoginViewModel : ViewModel() {

    private val repository = AuthRepository()
    private val prefs = PreferencesManager(ServerManagerApp.instance)

    private val _uiState = MutableStateFlow(LoginUiState())
    val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            val savedToken = prefs.getToken()
            if (savedToken.isNotBlank()) {
                val savedUsername = prefs.getUsername()
                RetrofitClient.setToken(savedToken)
                _uiState.value = _uiState.value.copy(
                    isConnected = true,
                    username = savedUsername
                )
            }
        }
    }

    fun updateUsername(value: String) {
        _uiState.value = _uiState.value.copy(username = value, error = null)
    }

    fun updatePassword(value: String) {
        _uiState.value = _uiState.value.copy(password = value, error = null)
    }

    fun login() {
        val state = _uiState.value
        if (state.username.isBlank()) {
            _uiState.value = state.copy(error = "Please enter your username")
            return
        }
        if (state.password.isBlank()) {
            _uiState.value = state.copy(error = "Please enter your password")
            return
        }

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, error = null)
            val result = repository.login(state.username, state.password)
            result.fold(
                onSuccess = { loginResult ->
                    RetrofitClient.setToken(loginResult.token)
                    prefs.saveUserData(
                        loginResult.token, loginResult.userId,
                        loginResult.username, loginResult.email, loginResult.role
                    )
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        isConnected = true,
                        error = null
                    )
                },
                onFailure = { e ->
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        error = e.message ?: "Login failed"
                    )
                }
            )
        }
    }

    fun logout() {
        viewModelScope.launch {
            prefs.clear()
            RetrofitClient.setToken("")
            _uiState.value = LoginUiState()
        }
    }
}
