package com.swoosh.microblog.ui.tags

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.swoosh.microblog.data.model.GhostTagFull
import com.swoosh.microblog.data.repository.TagRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

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

    private val tagRepository = TagRepository(application)

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

    init {
        loadTags()
    }

    fun loadTags() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            tagRepository.fetchTags().fold(
                onSuccess = { tags ->
                    _uiState.update { it.copy(tags = tags, isLoading = false) }
                },
                onFailure = { e ->
                    _uiState.update { it.copy(isLoading = false, error = e.message) }
                }
            )
        }
    }

    fun updateSearchQuery(query: String) {
        _uiState.update { it.copy(searchQuery = query) }
    }

    fun startEditing(tag: GhostTagFull) {
        _uiState.update { it.copy(editingTag = tag) }
    }

    fun startCreating() {
        _uiState.update {
            it.copy(editingTag = GhostTagFull(name = ""))
        }
    }

    fun cancelEditing() {
        _uiState.update { it.copy(editingTag = null) }
    }

    fun saveTag(tag: GhostTagFull) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            if (tag.id != null) {
                // Update existing tag
                tagRepository.updateTag(tag.id, tag).fold(
                    onSuccess = {
                        _uiState.update { it.copy(editingTag = null) }
                        loadTags()
                    },
                    onFailure = { e ->
                        _uiState.update { it.copy(isLoading = false, error = e.message) }
                    }
                )
            } else {
                // Create new tag
                tagRepository.createTag(
                    name = tag.name,
                    description = tag.description,
                    accentColor = tag.accent_color
                ).fold(
                    onSuccess = {
                        _uiState.update { it.copy(editingTag = null) }
                        loadTags()
                    },
                    onFailure = { e ->
                        _uiState.update { it.copy(isLoading = false, error = e.message) }
                    }
                )
            }
        }
    }

    fun deleteTag(id: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            tagRepository.deleteTag(id).fold(
                onSuccess = {
                    _uiState.update { it.copy(editingTag = null) }
                    loadTags()
                },
                onFailure = { e ->
                    _uiState.update { it.copy(isLoading = false, error = e.message) }
                }
            )
        }
    }

    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}

data class TagsUiState(
    val tags: List<GhostTagFull> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
    val searchQuery: String = "",
    val editingTag: GhostTagFull? = null
) {
    val filteredTags: List<GhostTagFull>
        get() = if (searchQuery.isBlank()) tags
        else tags.filter { it.name.contains(searchQuery, ignoreCase = true) }
}
