package com.aiosman.ravenow.ui.account

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.UploadImage
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.ravenow.utils.TrtcHelper
import com.aiosman.ravenow.AppStore
import android.util.Log
import java.io.File

object AccountEditViewModel : ViewModel() {
    var name by mutableStateOf("")
    var bio by mutableStateOf("")
    var imageUrl by mutableStateOf<Uri?>(null)
    val accountService: AccountService = AccountServiceImpl()
    var profile by mutableStateOf<AccountProfileEntity?>(null)
    var croppedBitmap by mutableStateOf<Bitmap?>(null)
    var isUpdating by mutableStateOf(false)
    var isLoading by mutableStateOf(false)
    suspend fun reloadProfile(updateTrtcProfile:Boolean = false) {
        Log.d("AccountEditViewModel", "reloadProfile: 开始加载用户资料")
        isLoading = true
        try {
            Log.d("AccountEditViewModel", "reloadProfile: 调用API获取用户资料")
            accountService.getMyAccountProfile().let {
                Log.d("AccountEditViewModel", "reloadProfile: 成功获取用户资料 - nickName: ${it.nickName}")
                profile = it
                name = it.nickName
                bio = it.bio
                // 清除之前裁剪的图片
                croppedBitmap = null
                if (updateTrtcProfile) {
                    TrtcHelper.updateTrtcProfile(
                        it.nickName,
                        it.rawAvatar
                    )
                }
            }
        } catch (e: Exception) {
            // 处理异常，避免UI消失
            Log.e("AccountEditViewModel", "reloadProfile: 加载用户资料失败", e)
            e.printStackTrace()
            // 如果是首次加载失败，至少保持之前的profile不变
            // 这样UI不会突然消失
        } finally {
            Log.d("AccountEditViewModel", "reloadProfile: 加载完成，isLoading设为false")
            isLoading = false
        }
    }

    fun resetToOriginalData() {
        profile?.let {
            name = it.nickName
            bio = it.bio
            // 清除之前裁剪的图片
            croppedBitmap = null
        }
    }


    suspend fun updateUserProfile(context: Context) {
        val newAvatar = croppedBitmap?.let {
            val file = File(context.cacheDir, "avatar.jpg")
            it.compress(Bitmap.CompressFormat.JPEG, 100, file.outputStream())
            UploadImage(file, "avatar.jpg", "", "jpg")
        }
        // 去除换行符，确保昵称和个人简介不包含换行
        val cleanName = name.trim().replace("\n", "").replace("\r", "")
        val cleanBio = bio.trim().replace("\n", "").replace("\r", "")
        
        val newName = if (cleanName == profile?.nickName) null else cleanName
        accountService.updateProfile(
            avatar = newAvatar,
            banner = null,
            nickName = newName,
            bio = cleanBio
        )
        // 刷新用户资料
        reloadProfile()
        // 刷新个人资料页面的用户资料
        MyProfileViewModel.loadUserProfile()
    }

    /**
     * 重置ViewModel状态
     * 用于用户登出或切换账号时清理数据
     */
    fun ResetModel() {
        Log.d("AccountEditViewModel", "ResetModel: 重置ViewModel状态")
        profile = null
        name = ""
        bio = ""
        imageUrl = null
        croppedBitmap = null
        isUpdating = false
        isLoading = false
    }
}