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.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import feufaro.composeapp.generated.resources.Res
import feufaro.composeapp.generated.resources.compose_multiplatform
import feufaro.composeapp.generated.resources.icon
import mg.dot.feufaro.FileRepository
import mg.dot.feufaro.MGButton
import mg.dot.feufaro.solfa.ColorPrefixA
import mg.dot.feufaro.solfa.ColorPrefixB
import mg.dot.feufaro.solfa.ColorValue
import org.jetbrains.compose.resources.painterResource
import java.io.ByteArrayOutputStream
import java.util.zip.GZIPOutputStream
import kotlin.io.encoding.Base64

@Composable
fun QRDisplay(sharedScreenModel: SharedScreenModel, fileRepository: FileRepository) {

    val content by sharedScreenModel.fileContent
    val path by sharedScreenModel.activeFilePath
    val fileName = path.substringAfterLast('/').substringAfterLast(':')

    val qrCodeImage by produceState<ImageBitmap?>(initialValue = null, content, path) {
        val expandedSource = expandInclusions(
            content = content,
            currentFilePath = path,
            fileRepository = fileRepository
        )
        if(expandedSource.isNotEmpty()) {
            val bos = ByteArrayOutputStream()
            GZIPOutputStream(bos).use { it.write(expandedSource.toByteArray(Charsets.UTF_8)) }
            val compressedBytes = bos.toByteArray()

            val compressedData = Base64.UrlSafe.encode(compressedBytes).trim('=')

            val uri = "feufaro://song?file=${compressedData}&name=$fileName"
            value = generateQRCode(uri, size = 1200)
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.4f))
            .clickable { sharedScreenModel.toggleQRCodeVisibility() },
        contentAlignment = Alignment.BottomCenter
    ) {
        BoxWithConstraints(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.BottomCenter
        ) {
            val screenHeight = maxHeight
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .widthIn(max = 450.dp)
                    .height(screenHeight * 0.85f)
                    .clickable(enabled = false) {}
                    .shadow(16.dp, shape = RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp)),
                shape = RoundedCornerShape(topStart = 32.dp, topEnd = 32.dp),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp)
                        .padding(top = 12.dp, bottom = 32.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(width = 40.dp, height = 4.dp)
                            .clip(CircleShape)
                            .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f))
                    )

                    Spacer(modifier = Modifier.height(12.dp))
                    Text(
                        text = "Scanner ce QR Code",
                        style = MaterialTheme.typography.titleLarge.copy(
                            fontWeight = FontWeight.Bold,
                            fontSize = 22.sp
                        )
                    )

                    Spacer(modifier = Modifier.height(5.dp))

                    if (qrCodeImage != null) {
                        Box(
                            contentAlignment = Alignment.Center,
                            modifier = Modifier
                                .weight(10f)
                                .fillMaxHeight(1f)
                                .aspectRatio(1f)
                                .clip(RoundedCornerShape(24.dp))
                                .padding(12.dp)
                        ) {
                            Image(
                                bitmap = qrCodeImage!!,
                                contentDescription = "Code QR du fichier actif",
                                modifier = Modifier.fillMaxSize()
                            )

                            Box(
                                modifier = Modifier
                                    .fillMaxHeight(0.18f)
                                    .aspectRatio(1f)
                                    .background(Color.White, shape = RoundedCornerShape(12.dp))
                                    .padding(4.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Image(
                                    painter = painterResource(Res.drawable.icon),
                                    contentDescription = "App Logo",
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .clip(RoundedCornerShape(8.dp))
                                )
                            }
                        }
                    } else {
                        Box(
                            modifier = Modifier.size(280.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(48.dp),
                                    color = ColorPrefixA,
                                    strokeWidth = 4.dp,
                                    trackColor = ColorPrefixB.copy(alpha = 0.2f)
                                )
                                Spacer(modifier = Modifier.height(16.dp))
                                Text(
                                    text = "Génération du QR Code...",
                                    style = MaterialTheme.typography.bodyMedium.copy(
                                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                                    )
                                )
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(2.dp))

                    Text(
                        text = "Partager et charger rapidement cette partition",
                        style = MaterialTheme.typography.bodyMedium.copy(
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
                            letterSpacing = 0.2.sp
                        )
                    )

                    Spacer(modifier = Modifier.height(2.dp))
                    Button(
                        onClick = { sharedScreenModel.toggleQRCodeVisibility() },
                        modifier = Modifier
                            .width(450.dp),

                    ) {
                        Text(
                            text = "Fermer",
                            fontWeight = FontWeight.Bold,
                            fontSize = 16.sp
                        )
                    }
                }
            }
        }
    }
}

private suspend fun expandInclusions(
    content: String?,
    currentFilePath: String,
    fileRepository: FileRepository
): String {
    if(content.isNullOrEmpty()) return ""
    val lines = content.split("\n")
    val result = StringBuilder()
    val lastSlash = currentFilePath.lastIndexOf('/')
    val directory = if (lastSlash != -1) currentFilePath.substring(0, lastSlash + 1) else ""

    lines.forEach { line ->
        if (line.startsWith("I0:")) {
            try {
                val parts = line.substring(3).split(":")
                val fileName = parts[0]
                val ignorePattern = if (parts.size > 1) parts[1] else ""

                val fullPath = directory + fileName
                val includedLines = fileRepository.readFileLines(fullPath)

                val regexIgnore = if (ignorePattern.isNotEmpty()) Regex(ignorePattern) else null

                includedLines.forEach { incLine ->
                    if (regexIgnore == null || !regexIgnore.containsMatchIn(incLine)) {
                        result.append(incLine).append("\n")
                    }
                }
            } catch (e: Exception) {
                result.append("// Erreur inclusion: ${e.message}\n")
            }
        } else {
            result.append(line).append("\n")
        }
    }
    return result.toString().trimEnd()
}