package com.aiosman.ravenow.ui.agent

import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.UploadImage
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.PointService
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.entity.AgentEntity
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File

class AiPromptEditViewModel : ViewModel() {
    var chatAIId by mutableStateOf("")
    var title by mutableStateOf("")
    var desc by mutableStateOf("")
    var isPublic by mutableStateOf(true)
    var originalIsPublic by mutableStateOf(true)
    var paidForPrivacyEdit by mutableStateOf(false)
    var avatarUrl by mutableStateOf<String?>(null)
    var croppedBitmap by mutableStateOf<Bitmap?>(null)
    var isUpdating by mutableStateOf(false)
    var isLoading by mutableStateOf(false)
    var errorMessage by mutableStateOf<String?>(null)
    var isSelectingAvatar by mutableStateOf(false)
    
    /**
     * 加载Prompt详情
     */
    fun loadPromptDetail(chatAIId: String) {
        viewModelScope.launch {
            try {
                isLoading = true
                errorMessage = null
                this@AiPromptEditViewModel.chatAIId = chatAIId
                
                val response = ApiClient.api.getPromptDetail(chatAIId)
                val body = response.body()?.data ?: throw ServiceException("Failed to get prompt detail")
                
                // 填充数据
                title = body.title
                desc = body.desc
                isPublic = body.isPublic
                originalIsPublic = body.isPublic
                avatarUrl = "${ApiClient.BASE_API_URL}/outside${body.avatar}?token=${com.aiosman.ravenow.AppStore.token}"
                
                // 注意：Agent数据模型可能没有paidForPrivacyEdit字段，需要从其他地方获取
                // 暂时设为false，后续可以根据实际API响应调整
                paidForPrivacyEdit = false
                
            } catch (e: Exception) {
                Log.e("AiPromptEditViewModel", "Error loading prompt detail", e)
                errorMessage = "加载失败: ${e.message}"
            } finally {
                isLoading = false
            }
        }
    }
    
    /**
     * 更新Prompt
     */
    suspend fun updatePrompt(context: Context): AgentEntity? {
        try {
            isUpdating = true
            errorMessage = null
            
            // 准备头像文件
            val avatarFile = if (croppedBitmap != null) {
                val file = File(context.cacheDir, "agent_avatar_edit.jpg")
                croppedBitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, file.outputStream())
                UploadImage(file, "agent_avatar_edit.jpg", "", "jpg")
            } else {
                null
            }
            
            // 准备请求参数
            val textTitle = title.trim().toRequestBody("text/plain".toMediaTypeOrNull())
            val textDesc = desc.trim().toRequestBody("text/plain".toMediaTypeOrNull())
            val textValue = desc.trim().toRequestBody("text/plain".toMediaTypeOrNull()) // value通常和desc相同
            val isPublicBody = isPublic.toString().toRequestBody("text/plain".toMediaTypeOrNull())
            
            val avatarPart: MultipartBody.Part? = avatarFile?.let {
                val requestFile = it.file.asRequestBody("image/*".toMediaTypeOrNull())
                MultipartBody.Part.createFormData("avatar", it.filename, requestFile)
            }
            
            // 调用更新API
            val response = ApiClient.api.updatePrompt(
                promptId = chatAIId,
                avatar = avatarPart,
                title = textTitle,
                desc = textDesc,
                value = textValue,
                isPublic = isPublicBody
            )
            
            val body = response.body()?.data ?: throw ServiceException("Failed to update prompt")
            
            // 更新本地状态
            originalIsPublic = isPublic
            
            return body.toAgentEntity()
        } catch (e: Exception) {
            Log.e("AiPromptEditViewModel", "Error updating prompt", e)
            errorMessage = "更新失败: ${e.message}"
            throw e
        } finally {
            isUpdating = false
        }
    }
    
    /**
     * 验证输入
     */
    fun validate(): String? {
        return when {
            title.trim().isEmpty() -> "智能体名称不能为空"
            title.trim().length < 2 -> "智能体名称长度不能少于2个字符"
            title.trim().length > 20 -> "智能体名称长度不能超过20个字符"
            desc.trim().isEmpty() -> "智能体描述不能为空"
            desc.trim().length > 512 -> "智能体描述长度不能超过512个字符"
            else -> null
        }
    }
    
    /**
     * 判断是否需要付费解锁隐私切换
     */
    fun needsPrivacyPayment(): Boolean {
        // 如果已经解锁过，则不需要付费
        if (paidForPrivacyEdit) {
            return false
        }
        // 只有从公开（true）切换到私有（false）才需要付费
        return originalIsPublic == true && isPublic == false
    }
    
    /**
     * 获取解锁隐私权限的费用
     * @return 费用金额，如果无法获取则返回 0
     */
    fun getPrivacyCost(): Int {
        val rules = PointService.pointsRules.value
        val costRule = rules?.sub?.get(PointService.PointsRuleKey.SPEND_AGENT_PRIVATE)
        return when (costRule) {
            is PointService.RuleAmount.Fixed -> costRule.value
            is PointService.RuleAmount.Range -> costRule.min // 使用最小值作为默认费用
            null -> 0
        }
    }
    
    /**
     * 获取当前余额
     * @return 当前余额，如果无法获取则返回 0
     */
    fun getCurrentBalance(): Int {
        return PointService.pointsBalance.value?.balance ?: 0
    }
    
    /**
     * 计算消耗后余额
     * @param cost 费用
     * @return 消耗后余额
     */
    fun calculateBalanceAfterCost(cost: Int): Int {
        val currentBalance = getCurrentBalance()
        return (currentBalance - cost).coerceAtLeast(0)
    }
    
    /**
     * 检查余额是否充足
     * @param cost 费用
     * @return 是否充足
     */
    fun isBalanceSufficient(cost: Int): Boolean {
        return getCurrentBalance() >= cost
    }
    
    /**
     * 清空数据
     */
    fun clearData() {
        chatAIId = ""
        title = ""
        desc = ""
        isPublic = true
        originalIsPublic = true
        paidForPrivacyEdit = false
        avatarUrl = null
        croppedBitmap = null
        isUpdating = false
        isLoading = false
        errorMessage = null
        isSelectingAvatar = false
    }
}

