package mg.dot.feufaro.ui

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import mg.dot.feufaro.solfa.Transpose
import mg.dot.feufaro.viewmodel.PartitionMetadata
import mg.dot.feufaro.viewmodel.measureOptions


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewPartition(
    onCreate: (PartitionMetadata) -> Unit,
    onDismissRequest: () -> Unit,
    isAndroid: Boolean
) {
    val CardBg = MaterialTheme.colorScheme.background
    val FieldBg = MaterialTheme.colorScheme.surface
    val BorderColor = MaterialTheme.colorScheme.outline
    val TextPrimary = MaterialTheme.colorScheme.onSurface
    val TextSecondary = MaterialTheme.colorScheme.onSurfaceVariant
    val AccentBlue = MaterialTheme.colorScheme.primary
    val IconBg = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
    val ButtonBg = MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)


    var title by remember { mutableStateOf("") }
    var author by remember { mutableStateOf("") }
    var composer by remember { mutableStateOf("") }
    var rhythm by remember { mutableStateOf("") }
    var measure by remember { mutableStateOf("4/4") }
    var key by remember { mutableStateOf("C") }
    var url by remember { mutableStateOf("https://") }
    var keyMenuExpanded by remember { mutableStateOf(false) }
    var langMenuExpanded by remember { mutableStateOf(false) }
    val availableKeys = remember { Transpose.keyToNumber.toList() }
    var lang by remember { if(isAndroid) mutableStateOf("🇲🇬") else mutableStateOf("Malagasy") }
    val availableLang = remember { if(isAndroid) listOf("\uD83C\uDDFA\uD83C\uDDF8", "🇲🇬") else listOf("Anglais", "Malagasy") }

    val fieldColors = OutlinedTextFieldDefaults.colors(
        focusedBorderColor = AccentBlue,
        unfocusedBorderColor = BorderColor,
        focusedTextColor = TextPrimary,
        unfocusedTextColor = TextPrimary,
        focusedLabelColor = TextSecondary,
        unfocusedLabelColor = TextSecondary,
        cursorColor = AccentBlue,
        focusedContainerColor = FieldBg,
        unfocusedContainerColor = FieldBg,
        focusedPlaceholderColor = TextSecondary,
        unfocusedPlaceholderColor = TextSecondary,
    )

    var measureMenuExpanded by remember { mutableStateOf(false) }

    Dialog(
        onDismissRequest = onDismissRequest,
        properties = DialogProperties(
            usePlatformDefaultWidth = false
        )
    ) {
        Card(
            colors = CardDefaults.cardColors(containerColor = CardBg),
            modifier = Modifier
                .fillMaxWidth(if(isAndroid) 0.9f else 0.55f)
                .pointerInput(Unit) {
                    detectTapGestures {  }
                },
            shape = RoundedCornerShape(24.dp),
            border = BorderStroke(1.dp, BorderColor.copy(alpha = 0.2f)),
            elevation = CardDefaults.cardElevation(defaultElevation = 16.dp)
        ) {
            Column(
                modifier = Modifier
                    .padding(20.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Box(
                        modifier = Modifier
                            .size(48.dp)
                            .background(IconBg, CircleShape),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Filled.MusicNote,
                            contentDescription = null,
                            tint = AccentBlue
                        )
                    }
                    Spacer(Modifier.width(12.dp))
                    Column {
                        Text(
                            "Nouvelle partition",
                            color = TextPrimary,
                            style = MaterialTheme.typography.titleMedium
                        )
                        Text(
                            "Renseigner les informations de la partition",
                            color = TextSecondary,
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }

                OutlinedTextField(
                    value = title,
                    onValueChange = { title = it },
                    label = { Text("Titre") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = fieldColors,
                    textStyle = MaterialTheme.typography.titleMedium
                )

                Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                    OutlinedTextField(
                        value = author,
                        onValueChange = { author = it },
                        label = { Text("Auteur") },
                        singleLine = true,
                        modifier = Modifier.weight(1f),
                        shape = RoundedCornerShape(12.dp),
                        colors = fieldColors,
                        textStyle = MaterialTheme.typography.titleMedium
                    )

                    OutlinedTextField(
                        value = composer,
                        onValueChange = { composer = it },
                        label = { Text("Compositeur / arrangeur") },
                        singleLine = true,
                        modifier = Modifier.weight(1f),
                        shape = RoundedCornerShape(12.dp),
                        colors = fieldColors,
                        textStyle = MaterialTheme.typography.titleMedium
                    )
                }

                Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                    ExposedDropdownMenuBox(
                        expanded = keyMenuExpanded,
                        onExpandedChange = { keyMenuExpanded = it },
                        modifier = Modifier.weight(1f)
                    ) {
                        OutlinedTextField(
                            value = key,
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("Tonalité") },
                            trailingIcon = {
                                ExposedDropdownMenuDefaults.TrailingIcon(expanded = keyMenuExpanded)
                            },
                            modifier = Modifier
                                .menuAnchor(MenuAnchorType.PrimaryEditable)
                                .fillMaxWidth(),
                            shape = RoundedCornerShape(12.dp),
                            colors = fieldColors
                        )
                        ExposedDropdownMenu(
                            expanded = keyMenuExpanded,
                            onDismissRequest = { keyMenuExpanded = false },
                            modifier = Modifier.background(CardBg)
                        ) {
                            availableKeys.forEach { kKey ->
                                DropdownMenuItem(
                                    text = { Text(kKey, color = TextPrimary) },
                                    onClick = {
                                        key = kKey
                                        keyMenuExpanded = false
                                    }
                                )
                            }
                        }
                    }

                    OutlinedTextField(
                        value = rhythm,
                        onValueChange = { rhythm = it },
                        label = { Text("Mesure poétique") },
                        placeholder = { Text("8.7.8.7.D") },
                        singleLine = true,
                        modifier = Modifier.weight(1f),
                        shape = RoundedCornerShape(12.dp),
                        colors = fieldColors,
                        textStyle = MaterialTheme.typography.titleMedium
                    )

                    ExposedDropdownMenuBox(
                        expanded = langMenuExpanded,
                        onExpandedChange = { langMenuExpanded = it },
                        modifier = Modifier.weight(1f)
                    ) {
                        OutlinedTextField(
                            value = lang,
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("Langue des paroles") },
                            trailingIcon = {
                                ExposedDropdownMenuDefaults.TrailingIcon(expanded = langMenuExpanded)
                            },
                            modifier = Modifier
                                .menuAnchor(MenuAnchorType.PrimaryEditable)
                                .fillMaxWidth(),
                            shape = RoundedCornerShape(12.dp),
                            colors = fieldColors
                        )
                        ExposedDropdownMenu(
                            expanded = langMenuExpanded,
                            onDismissRequest = { langMenuExpanded = false },
                            modifier = Modifier.background(CardBg)
                        ) {
                            availableLang.forEach { klang ->
                                DropdownMenuItem(
                                    text = { Text(klang, color = TextPrimary) },
                                    onClick = {
                                        lang = klang
                                        langMenuExpanded = false
                                    }
                                )
                            }
                        }
                    }
                }

                Column(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Text(
                        "Mesure",
                        color = TextSecondary,
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.padding(start = 4.dp)
                    )
                    FlowRow(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        measureOptions.forEach { (mVal, mStyle) ->
                            val isSelected = (measure == mVal)
                            val tooltipState = rememberTooltipState()

                            TooltipBox(
                                positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                                tooltip = {
                                    PlainTooltip {
                                        Text("$mStyle")
                                    }
                                },
                                state = tooltipState
                            ) {
                                Surface(
                                    selected = isSelected,
                                    onClick = { measure = mVal },
                                    modifier = Modifier
                                        .width(70.dp)
                                        .height(48.dp),
                                    shape = RoundedCornerShape(12.dp),
                                    color = if (isSelected) AccentBlue.copy(alpha = 0.12f) else FieldBg,
                                    border = BorderStroke(
                                        width = if (isSelected) 1.5.dp else 1.dp,
                                        color = if (isSelected) AccentBlue else BorderColor
                                    )
                                ) {
                                    Row(
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .padding(horizontal = 8.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.SpaceBetween
                                    ) {
                                        Text(
                                            text = mVal,
                                            color = if (isSelected) AccentBlue else TextPrimary,
                                            style = MaterialTheme.typography.bodyLarge,
                                            fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
                                        )

                                        RadioButton(
                                            selected = isSelected,
                                            onClick = null,
                                            colors = RadioButtonDefaults.colors(
                                                selectedColor = AccentBlue,
                                                unselectedColor = TextSecondary
                                            ),
                                            modifier = Modifier.size(20.dp)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }


                OutlinedTextField(
                    value = url,
                    onValueChange = { url = it },
                    label = { Text("Source (URL)") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = fieldColors,
                    textStyle = MaterialTheme.typography.titleMedium
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    OutlinedButton(
                        onClick = onDismissRequest,
                        modifier = Modifier.weight(1f),
                        border = BorderStroke(0.5.dp, BorderColor),
                        colors = ButtonDefaults.outlinedButtonColors(contentColor = TextSecondary),
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        Text("Annuler")
                    }

                    Button(
                        onClick = {
                            onCreate(
                                PartitionMetadata(
                                    title = title,
                                    author = author,
                                    composer = composer,
                                    rhythm = rhythm,
                                    measure = measure,
                                    key = key,
                                    url = url,
                                    language = if(lang == "\uD83C\uDDF2\uD83C\uDDEC") "Malagasy" else "Anglais"
                                )
                            )
                        },
                        enabled = title.isNotBlank(),
                        modifier = Modifier.weight(2f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = ButtonBg,
                            contentColor = AccentBlue,
                            disabledContainerColor = ButtonBg.copy(alpha = 0.4f),
                            disabledContentColor = AccentBlue.copy(alpha = 0.4f),
                        ),
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Add,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(Modifier.width(6.dp))
                        Text("Créer la partition")
                    }
                }
            }
        }
    }
}