package com.tt.honeyDue.ui.screens.task

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.models.TaskCreateRequest
import com.tt.honeyDue.models.TaskResponse
import com.tt.honeyDue.models.TaskSuggestionResponse
import com.tt.honeyDue.models.TaskSuggestionsResponse
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.network.ApiResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * ViewModel for the standalone TaskSuggestionsScreen — the non-onboarding
 * path into personalized task suggestions. Event naming matches the
 * non-onboarding convention used by the templates browser.
 */
class TaskSuggestionsViewModel(
    private val residenceId: Int,
    private val loadSuggestions: suspend () -> ApiResult<TaskSuggestionsResponse> = {
        APILayer.getTaskSuggestions(residenceId)
    },
    private val createTask: suspend (TaskCreateRequest) -> ApiResult<TaskResponse> = { req ->
        APILayer.createTask(req)
    },
    private val analytics: (String, Map<String, Any>) -> Unit = { name, props ->
        PostHogAnalytics.capture(name, props)
    }
) : ViewModel() {

    private val _suggestionsState =
        MutableStateFlow<ApiResult<TaskSuggestionsResponse>>(ApiResult.Idle)
    val suggestionsState: StateFlow<ApiResult<TaskSuggestionsResponse>> =
        _suggestionsState.asStateFlow()

    private val _acceptState = MutableStateFlow<ApiResult<TaskResponse>>(ApiResult.Idle)
    val acceptState: StateFlow<ApiResult<TaskResponse>> = _acceptState.asStateFlow()

    var lastAcceptedTemplateId: Int? = null
        private set

    fun load() {
        viewModelScope.launch {
            _suggestionsState.value = ApiResult.Loading
            _suggestionsState.value = loadSuggestions()
        }
    }

    fun retry() = load()

    fun accept(suggestion: TaskSuggestionResponse) {
        val template = suggestion.template
        val request = TaskCreateRequest(
            residenceId = residenceId,
            title = template.title,
            description = template.description.takeIf { it.isNotBlank() },
            categoryId = template.categoryId,
            frequencyId = template.frequencyId,
            templateId = template.id
        )

        viewModelScope.launch {
            _acceptState.value = ApiResult.Loading
            val result = createTask(request)
            _acceptState.value = when (result) {
                is ApiResult.Success -> {
                    lastAcceptedTemplateId = template.id
                    analytics(
                        EVENT_TASK_SUGGESTION_ACCEPTED,
                        buildMap {
                            put("template_id", template.id)
                            put("relevance_score", suggestion.relevanceScore)
                            template.categoryId?.let { put("category_id", it) }
                        }
                    )
                    ApiResult.Success(result.data)
                }
                is ApiResult.Error -> result
                ApiResult.Loading -> ApiResult.Loading
                ApiResult.Idle -> ApiResult.Idle
            }
        }
    }

    fun resetAcceptState() {
        _acceptState.value = ApiResult.Idle
        lastAcceptedTemplateId = null
    }

    companion object {
        /**
         * Non-onboarding analytics event for a single accepted suggestion.
         */
        const val EVENT_TASK_SUGGESTION_ACCEPTED = "task_suggestion_accepted"
    }
}
