package de.trainingstagebuch.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.trainingstagebuch.app.R
import de.trainingstagebuch.app.repository.CreateClubResult
import de.trainingstagebuch.app.services.AppServices
import de.trainingstagebuch.app.utils.ErrorMessageFormatter
import de.trainingstagebuch.app.utils.UiText
import de.trainingstagebuch.app.utils.ViewModelStateUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class CreateClubViewModel(application: Application) : AndroidViewModel(application) {

    private val homeService = AppServices.homeService
    private val authService = AppServices.authService

    private val _state = MutableStateFlow(CreateClubUiState())
    val state: StateFlow<CreateClubUiState> = _state.asStateFlow()

    fun onNameChanged(value: String) {
        _state.update { it.copy(name = value) }
    }

    fun createClub() {
        val name = _state.value.name.trim()
        if (name.length < 3) {
            _state.update {
                it.copy(
                    status = CreateClubStatus.Error,
                    errorMessage = UiText(R.string.create_club_name_required)
                )
            }
            return
        }

        viewModelScope.launch {
            _state.update { it.copy(status = CreateClubStatus.Loading, errorMessage = null, successMessage = null) }
            when (val result = homeService.createClub(name)) {
                is CreateClubResult.Success -> {
                    val session = authService.session.first()
                    if (!result.createdClubId.isNullOrBlank()) {
                        authService.saveCurrentClub(
                            token = session.token,
                            username = session.username,
                            clubId = result.createdClubId
                        )
                    }
                    _state.update {
                        it.copy(
                            status = CreateClubStatus.Success,
                            successMessage = UiText(R.string.create_club_success_default)
                        )
                    }
                }

                is CreateClubResult.Error -> {
                    val message = ErrorMessageFormatter.dynamicWithOptionalCode(result.message, result.code)
                    _state.update {
                        it.copy(
                            status = CreateClubStatus.Error,
                            errorMessage = ViewModelStateUtils.normalizeUiText(message)
                        )
                    }
                }
            }
        }
    }

    fun resetToIdle() {
        _state.update { it.copy(status = CreateClubStatus.Idle, errorMessage = null) }
    }
}

data class CreateClubUiState(
    val name: String = "",
    val status: CreateClubStatus = CreateClubStatus.Idle,
    val errorMessage: UiText? = null,
    val successMessage: UiText? = null
)

enum class CreateClubStatus {
    Idle,
    Loading,
    Success,
    Error
}
