package mg.dot.feufaro.ui

import SharedScreenModel
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.unit.dp
import java.io.ByteArrayOutputStream
import java.net.URLEncoder
import java.util.zip.GZIPOutputStream
import kotlin.io.encoding.Base64

@Composable
fun QRDisplay(sharedScreenModel: SharedScreenModel) {

    val content by sharedScreenModel.fileContent

    fun compressAndEncode(content: String?): String {
        val bos = ByteArrayOutputStream()
        GZIPOutputStream(bos).use { it.write(content?.toByteArray(Charsets.UTF_8)) }
        val compressedBytes = bos.toByteArray()
        return Base64.UrlSafe.encode(compressedBytes).trim('=')
    }

    val compressedData = compressAndEncode(content)
    val uri = "feufaro://song?file=$compressedData"
//    val encodedContent = URLEncoder.encode(content, "UTF-8")
//    val uri = "feufaro://song?file=$encodedContent"

    val qrCodeImage = remember(content) {
        if (content != null) {
            generateQRCode(uri, size = 800)
        } else {
            null
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.5f)) // Fond semi-transparent
            .clickable { sharedScreenModel.toggleQRCodeVisibility() } // Fermer au clic
            .imePadding()
            .systemBarsPadding(),
        contentAlignment = Alignment.Center
    ) {
        Card(
            modifier = Modifier.wrapContentSize().shadow(16.dp, shape = MaterialTheme.shapes.large)
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.padding(24.dp)
            ) {
                Text("Scanner pour ouvrir ce partition")
                if (qrCodeImage != null) {
                    Image(
                        bitmap = qrCodeImage,
                        contentDescription = "Code QR du fichier actif",
                        modifier = Modifier.size(400.dp)
                    )
                } else {
                    Text("Chargement du Code QR ou contenu vide...", modifier = Modifier.padding(16.dp))
                }
            }
        }
    }
}