package com.tt.honeyDue.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tt.honeyDue.models.TaskCompletionCreateRequest
import com.tt.honeyDue.models.TaskCompletionResponse
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.util.ImageCompressor
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class TaskCompletionViewModel : ViewModel() {

    private val _createCompletionState = MutableStateFlow<ApiResult<TaskCompletionResponse>>(ApiResult.Idle)
    val createCompletionState: StateFlow<ApiResult<TaskCompletionResponse>> = _createCompletionState

    fun createTaskCompletion(request: TaskCompletionCreateRequest) {
        viewModelScope.launch {
            _createCompletionState.value = ApiResult.Loading
            // Use APILayer which handles DataManager updates and summary refresh
            _createCompletionState.value = APILayer.createTaskCompletion(request)
        }
    }

    /**
     * Create task completion with images.
     *
     * @param request The completion request data
     * @param images List of ImageData (from platform-specific image pickers)
     */
    fun createTaskCompletionWithImages(
        request: TaskCompletionCreateRequest,
        images: List<com.tt.honeyDue.platform.ImageData> = emptyList()
    ) {
        viewModelScope.launch {
            _createCompletionState.value = ApiResult.Loading

            // Compress images and prepare for upload
            val compressedImages = images.map { ImageCompressor.compressImage(it) }
            val imageFileNames = images.mapIndexed { index, image ->
                // Always use .jpg extension since we compress to JPEG
                val baseName = image.fileName.ifBlank { "completion_$index" }
                if (baseName.endsWith(".jpg", ignoreCase = true) ||
                    baseName.endsWith(".jpeg", ignoreCase = true)) {
                    baseName
                } else {
                    // Remove any existing extension and add .jpg
                    baseName.substringBeforeLast('.', baseName) + ".jpg"
                }
            }

            // Use APILayer which handles DataManager updates and summary refresh
            _createCompletionState.value = APILayer.createTaskCompletionWithImages(
                request = request,
                images = compressedImages,
                imageFileNames = imageFileNames
            )
        }
    }

    fun resetCreateState() {
        _createCompletionState.value = ApiResult.Idle
    }
}
