package com.aiosman.ravenow.ui.post

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.ExifInterface
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.UploadImage
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentServiceImpl
import com.aiosman.ravenow.entity.createMultipartBody
import com.aiosman.ravenow.event.MomentAddEvent
import com.aiosman.ravenow.exp.rotate
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.ravenow.ui.modification.Modification
import com.aiosman.ravenow.utils.FileUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.UUID

data class ImageItem(
    val uri: String,
    val id: String,
    val bitmap: Bitmap,
    val file: File
) {
    companion object {
        fun fromUri(context: Context,uri: String): ImageItem? {
           // 保存图片文件到临时文件夹
            context.contentResolver.openInputStream(Uri.parse(uri))?.use { inputStream ->
                val tempFileName = UUID.randomUUID().toString()
                val tempFile = File.createTempFile(tempFileName, null, context.cacheDir)
                FileOutputStream(tempFile).use { outputStream ->
                    inputStream.copyTo(outputStream)
                }

                // 读取图片文件为 Bitmap
                var bitmap = BitmapFactory.decodeFile(tempFile.absolutePath)
                // 读取文件exif，修正旋转
                val exif = ExifInterface(tempFile.absolutePath)
                bitmap = when (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) {
                    ExifInterface.ORIENTATION_ROTATE_90 -> bitmap.rotate(90)
                    ExifInterface.ORIENTATION_ROTATE_180 -> bitmap.rotate(180)
                    ExifInterface.ORIENTATION_ROTATE_270 -> bitmap.rotate(270)
                    else -> bitmap
                }
                // 保存 bitmap 到临时文件夹
                try {
                    val savedBitmapFilename = UUID.randomUUID().toString()
                    val bitmapFile = File.createTempFile(savedBitmapFilename, ".jpg", context.cacheDir)
                    FileOutputStream(bitmapFile).use { os ->
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os)
                    }
                    // 清理临时文件
                    tempFile.delete()
                    return ImageItem(
                        uri = Uri.fromFile(bitmapFile).toString(),
                        id = savedBitmapFilename,
                        bitmap = bitmap,
                        file = bitmapFile
                    )
                } catch (e: IOException) {
                    Log.e("NewPost", "Failed to save bitmap to file", e)
                    null
                }
            }
            return null
        }
    }
}
data class DraftImageItem(
    val uri: String,
    val id: String,
    val filename: String
){
    companion object {
        fun fromImageItem(imageItem: ImageItem): DraftImageItem {
            return DraftImageItem(imageItem.uri, imageItem.id, imageItem.file.name)
        }
    }
}
data class Draft(
    val textContent: String,
    val imageList: List<DraftImageItem>
)
object NewPostViewModel : ViewModel() {
    var momentService: MomentService = MomentServiceImpl()
    var textContent by mutableStateOf("")
    var aiTextContent by mutableStateOf("")
    var searchPlaceAddressResult by mutableStateOf<SearchPlaceAddressResult?>(null)
    var modificationList by mutableStateOf<List<Modification>>(listOf())
    var imageList by mutableStateOf(listOf<ImageItem>())
    var relPostId by mutableStateOf<Int?>(null)
    var relMoment by mutableStateOf<MomentEntity?>(null)
    var currentPhotoUri: Uri? = null
    var draft: Draft? = null
    // watch textContent change and save draft
//    fun saveDraft() {
//        draft = Draft(textContent, imageList.map {
//            DraftImageItem(it.uri, it.id, it.bitmap)
//        })
//    }
    fun asNewPost() {
        textContent = ""
        aiTextContent = ""
        searchPlaceAddressResult = null
        modificationList = listOf()
        imageList = listOf()
        relPostId = null
    }

    fun asNewPostWithImageUris(imageUris: List<String>) {
        textContent = ""
        searchPlaceAddressResult = null
        modificationList = listOf()
//        imageList = imageUris.map {
//            ImageItem(it, UUID.randomUUID().toString())
//        }
        relPostId = null
    }

    suspend fun uriToFile(context: Context, uri: Uri): File {
        val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
        val tempFile = withContext(Dispatchers.IO) {
            File.createTempFile("temp", null, context.cacheDir)
        }
        inputStream?.use { input ->
            FileOutputStream(tempFile).use { output ->
                input.copyTo(output)
            }
        }
        return tempFile
    }

    fun validateMoment(): String? {
        if (imageList.isEmpty()) {
            return "Please select at least one image"
        }
        return null
    }

    suspend fun createMoment(context: Context, onUploadProgress: (Float) -> Unit) {
        val uploadImageList = emptyList<UploadImage>().toMutableList()
        var index = 0
        for (item in imageList) {
            // 保存图片到本地
            FileUtil.bitmapToJPG(context, item.bitmap, UUID.randomUUID().toString())
                ?.let { savedImageUri ->
                    // 读取保存的图片文件
                    uriToFile(context, savedImageUri).let { file ->
                        uploadImageList += UploadImage(file, file.name, item.uri, "jpg")
                    }
                }
            // 在上传过程中调用 onUploadProgress 更新进度
            onUploadProgress(((index / imageList.size).toFloat())) // progressValue 是当前上传进度，例如 0.5 表示 50%
            index += 1
        }
        aiTextContent = ""
        val result = momentService.createMoment(textContent, 1, uploadImageList, relPostId)
        // 刷新个人动态
        MyProfileViewModel.loadProfile(pullRefresh = true)
        EventBus.getDefault().post(MomentAddEvent(result))
    }

    suspend fun agentMoment(textContent: String,) {
        aiTextContent = momentService.agentMoment(textContent)
    }

    suspend fun init() {
        relPostId?.let {
            val moment = momentService.getMomentById(it)
            relMoment = moment
        }
    }

    fun deleteImage(index: Int) {
        if (index >= 0 && index < imageList.size) {
            imageList = imageList.toMutableList().apply {
                removeAt(index)
            }
        }
    }
}