package com.aiosman.ravenow.ui.composables

import android.content.Context
import android.graphics.Bitmap
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.core.graphics.drawable.toBitmap
import coil.ImageLoader
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.request.SuccessResult
import com.aiosman.ravenow.utils.Utils.getImageLoader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * CustomAsyncImage 组件使用说明：
 * 
 * @param context 上下文，可选
 * @param imageUrl 图片URL或Bitmap对象
 * @param contentDescription 图片描述
 * @param modifier 修饰符
 * @param blurHash 模糊哈希值（暂未使用）
 * @param placeholderRes 加载时显示的占位符图片资源ID
 * @param errorRes 加载失败时显示的错误图片资源ID
 * @param defaultRes 当imageUrl为空或null时显示的默认图片资源ID（优先级最高）
 * @param contentScale 图片缩放模式
 * 
 * 使用示例：
 * CustomAsyncImage(
 *     imageUrl = "https://example.com/image.jpg",
 *     contentDescription = "用户头像",
 *     defaultRes = R.mipmap.default_avatar,
 *     placeholderRes = R.mipmap.loading_placeholder,
 *     errorRes = R.mipmap.error_image
 * )
 */
@Composable
fun rememberImageBitmap(imageUrl: String, imageLoader: ImageLoader): Bitmap? {
    val context = LocalContext.current
    var bitmap by remember { mutableStateOf<Bitmap?>(null) }

    LaunchedEffect(imageUrl) {
        val request = ImageRequest.Builder(context)
            .data(imageUrl)
            .crossfade(true)
            .build()

        val result = withContext(Dispatchers.IO) {
            (imageLoader.execute(request) as? SuccessResult)?.drawable?.toBitmap()
        }

        bitmap = result
    }

    return bitmap
}

@Composable
fun CustomAsyncImage(
    context: Context? = null,
    imageUrl: Any?,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    blurHash: String? = null,
    @DrawableRes
    placeholderRes: Int? = null,
    @DrawableRes
    errorRes: Int? = null,
    @DrawableRes
    defaultRes: Int? = null,
    contentScale: ContentScale = ContentScale.Crop,
    showShimmer: Boolean = true
) {
    val localContext = LocalContext.current

    // 使用remember来缓存ImageLoader，避免重复创建
    val imageLoader = remember { getImageLoader(context ?: localContext) }

    // 处理 imageUrl 为 null 或空字符串的情况
    if (imageUrl == null || imageUrl == "") {
        // 优先使用 defaultRes，然后是 placeholderRes
        val fallbackRes = defaultRes ?: placeholderRes
        if (fallbackRes != null) {
            if (showShimmer) {
                SimpleShimmer(modifier = modifier) {
                    Image(
                        painter = androidx.compose.ui.res.painterResource(fallbackRes),
                        contentDescription = contentDescription,
                        modifier = Modifier.fillMaxSize(),
                        contentScale = contentScale
                    )
                }
            } else {
                Image(
                    painter = androidx.compose.ui.res.painterResource(fallbackRes),
                    contentDescription = contentDescription,
                    modifier = modifier,
                    contentScale = contentScale
                )
            }
            return
        }
    }

    // 处理 Bitmap 类型
    if (imageUrl is Bitmap) {
        if (showShimmer) {
            SimpleShimmer(modifier = modifier) {
                Image(
                    bitmap = imageUrl.asImageBitmap(),
                    contentDescription = contentDescription,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = contentScale
                )
            }
        } else {
            Image(
                bitmap = imageUrl.asImageBitmap(),
                contentDescription = contentDescription,
                modifier = modifier,
                contentScale = contentScale
            )
        }
        return
    }

    // 处理字符串URL
    if (showShimmer) {
        var isLoading by remember { mutableStateOf(true) }
        
        Box(modifier = modifier) {
            AsyncImage(
                model = ImageRequest.Builder(context ?: localContext)
                    .data(imageUrl)
                    .crossfade(200)
                    .memoryCachePolicy(coil.request.CachePolicy.ENABLED)
                    .diskCachePolicy(coil.request.CachePolicy.ENABLED)
                    .apply {
                        // 设置占位符图片
                        if (placeholderRes != null) {
                            placeholder(placeholderRes)
                        }
                        // 设置错误时显示的图片
                        if (errorRes != null) {
                            error(errorRes)
                        }
                    }
                    .build(),
                contentDescription = contentDescription,
                modifier = Modifier.fillMaxSize(),
                contentScale = contentScale,
                imageLoader = imageLoader,
                onLoading = { isLoading = true },
                onSuccess = { isLoading = false },
                onError = { isLoading = false }
            )
            
            // 只在加载时显示shimmer
            if (isLoading) {
                SimpleShimmer(modifier = Modifier.fillMaxSize()) {
                    Box(modifier = Modifier.fillMaxSize())
                }
            }
        }
    } else {
        AsyncImage(
            model = ImageRequest.Builder(context ?: localContext)
                .data(imageUrl)
                .crossfade(200)
                .memoryCachePolicy(coil.request.CachePolicy.ENABLED)
                .diskCachePolicy(coil.request.CachePolicy.ENABLED)
                .apply {
                    // 设置占位符图片
                    if (placeholderRes != null) {
                        placeholder(placeholderRes)
                    }
                    // 设置错误时显示的图片
                    if (errorRes != null) {
                        error(errorRes)
                    }
                }
                .build(),
            contentDescription = contentDescription,
            modifier = modifier,
            contentScale = contentScale,
            imageLoader = imageLoader
        )
    }
}

/*
使用示例：

1. 基本使用（带默认图片）：
CustomAsyncImage(
    imageUrl = user.avatar,
    contentDescription = "用户头像",
    defaultRes = R.mipmap.default_avatar
)

2. 完整配置：
CustomAsyncImage(
    imageUrl = "https://example.com/image.jpg",
    contentDescription = "产品图片",
    defaultRes = R.mipmap.default_product,
    placeholderRes = R.mipmap.loading_placeholder,
    errorRes = R.mipmap.error_image,
    contentScale = ContentScale.Crop
)

3. 处理空URL：
CustomAsyncImage(
    imageUrl = "", // 空字符串会显示默认图片
    contentDescription = "头像",
    defaultRes = R.mipmap.default_avatar
)

4. 处理Bitmap：
CustomAsyncImage(
    imageUrl = bitmapObject, // Bitmap对象会直接显示
    contentDescription = "裁剪后的图片"
)
*/