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)
    var bannerImageUrl by mutableStateOf<Uri?>(null)
    var bannerFile by mutableStateOf<File?>(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)
    // 本地扩展字段
    var mbti by mutableStateOf<String?>(null)
    var zodiac by mutableStateOf<String?>(null)
    // 保存原始值，用于取消时恢复
    private var originalName: String = ""
    private var originalBio: String = ""
    private var originalMbti: String? = null
    private var originalZodiac: String? = null
    suspend fun reloadProfile(updateTrtcProfile:Boolean = false, clearCroppedBitmap: 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
                // 保存原始值，用于取消时恢复
                originalName = it.nickName
                originalBio = it.bio
                // 只在明确要求时清除之前裁剪的图片（例如保存成功后）
                if (clearCroppedBitmap) {
                    croppedBitmap = null
                }
                // 读取本地扩展字段
                try {
                    val uid = it.id // 使用 profile 的 id，确保非空
                    val loadedMbti = com.aiosman.ravenow.AppStore.getUserMbti(uid)
                    val loadedZodiac = com.aiosman.ravenow.AppStore.getUserZodiac(uid)
                    mbti = loadedMbti
                    zodiac = loadedZodiac
                    // 保存原始值
                    originalMbti = loadedMbti
                    originalZodiac = loadedZodiac
                } catch (_: Exception) { }
                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() {
        // 恢复所有字段到原始值
        name = originalName
        bio = originalBio
        mbti = originalMbti
        zodiac = originalZodiac
        // 清除之前裁剪的图片和壁纸
        croppedBitmap = null
        bannerImageUrl = null
        bannerFile = 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 newBanner = bannerImageUrl?.let { uri ->
            bannerFile?.let { file ->
                val cursor = context.contentResolver.query(uri, null, null, null, null)
                var uploadBanner: UploadImage? = null
                cursor?.use { cur ->
                    val columnIndex = cur.getColumnIndex("_display_name")
                    if (cur.moveToFirst() && columnIndex != -1) {
                        val displayName = cur.getString(columnIndex)
                        val extension = displayName.substringAfterLast(".")
                        Log.d("AccountEditViewModel", "Banner file name: $displayName, extension: $extension")
                        uploadBanner = UploadImage(file, displayName, uri.toString(), extension)
                    } else {
                        // 如果无法获取文件名，使用默认值
                        val displayName = "banner.jpg"
                        val extension = "jpg"
                        uploadBanner = UploadImage(file, displayName, uri.toString(), extension)
                    }
                }
                uploadBanner
            }
        }
        
        // 去除换行符，确保昵称和个人简介不包含换行
        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 = newBanner,
            nickName = newName,
            bio = cleanBio
        )
        // 保存本地扩展字段
        try {
            profile?.id?.let { uid ->
                com.aiosman.ravenow.AppStore.setUserMbti(uid, mbti)
                com.aiosman.ravenow.AppStore.setUserZodiac(uid, zodiac)
            }
        } catch (_: Exception) { }
        // 清除背景图状态
        bannerImageUrl = null
        bannerFile = null
        // 刷新用户资料，保存成功后清除裁剪的图片
        reloadProfile(clearCroppedBitmap = true)
        // 刷新个人资料页面的用户资料
        MyProfileViewModel.loadUserProfile()
    }

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