package com.example.lexilearn.ui.components

import androidx.compose.foundation.Image
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import coil.compose.AsyncImage
import coil.compose.rememberAsyncImagePainter
import com.example.lexilearn.utils.getFirebaseImageUrl
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

@Composable
fun FirebaseImage(path: String, contentScale: ContentScale = ContentScale.None, modifier: Modifier = Modifier) {
    val imageUrlFlow = remember { MutableStateFlow<String?>(null) }
    val coroutineScope = rememberCoroutineScope()

    // Ambil URL dari Firebase Storage secara async
    LaunchedEffect(path) {
        coroutineScope.launch {
            getFirebaseImageUrl(path) { url ->
                imageUrlFlow.value = url
            }
        }
    }

    val imageUrl by imageUrlFlow.collectAsState()

    if (imageUrl != null) {
        AsyncImage(
            model = imageUrl,
            contentDescription = "Firebase Image",
            modifier = modifier,
            contentScale = contentScale
        )
    } else {
        Text(text = "Loading..")
    }
}
