package com.devlab.app.ui.profile

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.devlab.app.ServerManagerApp
import com.devlab.app.data.repository.ProfileRepository
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 ProfileUiState(
    val isLoading: Boolean = true,
    val username: String = "",
    val email: String = "",
    val role: String = "",
    val currentPassword: String = "",
    val newPassword: String = "",
    val confirmPassword: String = "",
    val isSaving: Boolean = false,
    val error: String? = null,
    val successMessage: String? = null,
    val emailError: String? = null,
    val newPasswordError: String? = null,
    val confirmPasswordError: String? = null
)

class ProfileViewModel : ViewModel() {

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

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

    fun loadProfile() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            val result = repository.getProfile()
            result.fold(
                onSuccess = { profile ->
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        username = profile.username,
                        email = profile.email,
                        role = profile.role
                    )
                },
                onFailure = { e ->
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        error = e.message ?: "Failed to load profile"
                    )
                }
            )
        }
    }

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

    fun updateCurrentPassword(value: String) {
        _uiState.value = _uiState.value.copy(currentPassword = value, error = null, successMessage = null)
    }

    fun updateNewPassword(value: String) {
        _uiState.value = _uiState.value.copy(newPassword = value, error = null, successMessage = null, newPasswordError = null)
    }

    fun updateConfirmPassword(value: String) {
        _uiState.value = _uiState.value.copy(confirmPassword = value, error = null, successMessage = null, confirmPasswordError = null)
    }

    fun save() {
        val state = _uiState.value
        var hasError = false

        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(state.email).matches()) {
            _uiState.value = _uiState.value.copy(emailError = "Enter a valid email address")
            hasError = true
        }
        if (state.newPassword.isNotBlank()) {
            if (state.newPassword.length < 8) {
                _uiState.value = _uiState.value.copy(newPasswordError = "Min 8 characters")
                hasError = true
            }
            if (state.confirmPassword != state.newPassword) {
                _uiState.value = _uiState.value.copy(confirmPasswordError = "Passwords do not match")
                hasError = true
            }
            if (state.currentPassword.isBlank()) {
                _uiState.value = _uiState.value.copy(error = "Enter current password to change password")
                hasError = true
            }
        }
        if (hasError) return

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isSaving = true, error = null, successMessage = null)
            val result = repository.updateProfile(
                state.email,
                state.currentPassword.takeIf { it.isNotBlank() },
                state.newPassword.takeIf { it.isNotBlank() },
                state.confirmPassword.takeIf { it.isNotBlank() }
            )
            result.fold(
                onSuccess = { message ->
                    prefs.saveProfile(state.email)
                    _uiState.value = _uiState.value.copy(
                        isSaving = false,
                        currentPassword = "",
                        newPassword = "",
                        confirmPassword = "",
                        successMessage = message
                    )
                },
                onFailure = { e ->
                    _uiState.value = _uiState.value.copy(
                        isSaving = false,
                        error = e.message ?: "Update failed"
                    )
                }
            )
        }
    }
}
