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, using the presigned-URL upload flow.
     *
     * For each image: compress, presign + POST direct to B2, collect the
     * upload_id. Once all uploads succeed, create the completion with the
     * collected upload_ids in a single JSON request. Bytes never traverse
     * our API server.
     *
     * If any individual upload fails, the whole batch fails — partial
     * pending_uploads rows are reaped server-side by the hourly cleanup
     * cron, so there's nothing to clean up client-side.
     *
     * @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

            val uploadIds = mutableListOf<Int>()
            for ((index, image) in images.withIndex()) {
                val compressed = ImageCompressor.compressImage(image)
                val fileName = run {
                    val base = image.fileName.ifBlank { "completion_$index" }
                    if (base.endsWith(".jpg", ignoreCase = true) ||
                        base.endsWith(".jpeg", ignoreCase = true)
                    ) base else base.substringBeforeLast('.', base) + ".jpg"
                }
                val uploadResult = APILayer.uploadImage(
                    category = "completion",
                    contentType = "image/jpeg",
                    bytes = compressed,
                    fileName = fileName,
                )
                when (uploadResult) {
                    is ApiResult.Success -> uploadIds += uploadResult.data
                    is ApiResult.Error -> {
                        _createCompletionState.value = ApiResult.Error(uploadResult.message, uploadResult.code)
                        return@launch
                    }
                    else -> {
                        _createCompletionState.value = ApiResult.Error("Upload failed in unexpected state")
                        return@launch
                    }
                }
            }

            val withUploads = if (uploadIds.isNotEmpty()) {
                request.copy(uploadIds = uploadIds.toList())
            } else {
                request
            }
            _createCompletionState.value = APILayer.createTaskCompletion(withUploads)
        }
    }

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