package com.aiosman.riderpro.ui.composables

import android.content.Context
import android.graphics.Bitmap
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.drawable.toDrawable
import coil.ImageLoader
import coil.compose.AsyncImage
import coil.compose.rememberAsyncImagePainter
import coil.compose.rememberImagePainter
import coil.request.ImageRequest
import coil.request.SuccessResult
import com.aiosman.riderpro.utils.BlurHashDecoder
import com.aiosman.riderpro.utils.Utils.getImageLoader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

@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: String?,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    blurHash: String? = null,
    @DrawableRes
    placeholderRes: Int? = null,
    contentScale: ContentScale = ContentScale.Crop
) {
    val localContext = LocalContext.current

    val imageLoader = getImageLoader(context ?: localContext)

    AsyncImage(
        model = ImageRequest.Builder(context ?: localContext)
            .data(imageUrl)
            .crossfade(200)
            .build(),
        contentDescription = contentDescription,
        modifier = modifier,
        contentScale = contentScale,
        imageLoader = imageLoader
    )
}