package com.example.polaritychecker

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.core.os.LocaleListCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.polaritychecker.ui.theme.PolarityCheckerTheme
import kotlinx.coroutines.flow.MutableStateFlow

class MainActivity : AppCompatActivity() {

    private val permissionGranted = MutableStateFlow(false)
    private val isPermanentlyDenied = MutableStateFlow(false)

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        permissionGranted.value = isGranted
        if (!isGranted) {
            isPermanentlyDenied.value = !shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        checkPermission()

        setContent {
            PolarityCheckerTheme {
                val granted by permissionGranted.collectAsState()
                val permanentlyDenied by isPermanentlyDenied.collectAsState()

                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    if (granted) {
                        PolarityCheckerApp()
                    } else {
                        PermissionScreen(
                            permanentlyDenied = permanentlyDenied,
                            onRequestPermission = {
                                requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
                            },
                            onOpenSettings = {
                                openAppSettings()
                            }
                        )
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkPermission()
    }

    private fun checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
            permissionGranted.value = true
        } else {
            permissionGranted.value = false
        }
    }

    private fun openAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", packageName, null)
        intent.data = uri
        startActivity(intent)
    }
}

@Composable
fun PermissionScreen(
    permanentlyDenied: Boolean,
    onRequestPermission: () -> Unit,
    onOpenSettings: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFF121212))
            .padding(32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = stringResource(R.string.permission_title),
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            color = Color.White,
            textAlign = TextAlign.Center
        )
        Spacer(modifier = Modifier.height(24.dp))
        Text(
            text = stringResource(R.string.permission_rationale),
            fontSize = 16.sp,
            color = Color.LightGray,
            textAlign = TextAlign.Center
        )
        Spacer(modifier = Modifier.height(48.dp))
        
        if (permanentlyDenied) {
            Text(
                text = stringResource(R.string.permission_permanently_denied),
                color = Color(0xFFFF1744),
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            Button(
                onClick = onOpenSettings,
                colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF29B6F6))
            ) {
                Text(stringResource(R.string.open_settings), color = Color(0xFF121212), fontWeight = FontWeight.Bold)
            }
        } else {
            Button(
                onClick = onRequestPermission,
                colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF00E676))
            ) {
                Text(stringResource(R.string.allow_microphone), color = Color(0xFF121212), fontWeight = FontWeight.Bold)
            }
        }
    }
}

@Composable
fun PolarityCheckerApp(viewModel: MainViewModel = viewModel()) {
    val selectedFrequency by viewModel.selectedFrequency.collectAsState()
    val isPlaying by viewModel.isPlaying.collectAsState()
    val isInverted by viewModel.isInverted.collectAsState()
    val threshold by viewModel.threshold.collectAsState()
    val inputLevel by viewModel.inputLevel.collectAsState()
    val polarityResult by viewModel.polarityResult.collectAsState()

    var showSettingsDialog by remember { mutableStateOf(false) }

    DisposableEffect(Unit) {
        viewModel.startAnalyzer()
        onDispose {
            viewModel.stopAnalyzer()
        }
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFF121212))
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(32.dp))

            // --- Main Result Indicator ---
            val waitingText = stringResource(R.string.status_waiting)
            val (indicatorColor, indicatorText, shadowColor) = when (polarityResult) {
                PolarityResult.WAITING -> Triple(Color(0xFF2A2A2A), waitingText, Color.Transparent)
                PolarityResult.POSITIVE -> Triple(Color(0xFF00E676), "+", Color(0x6600E676))
                PolarityResult.NEGATIVE -> Triple(Color(0xFFFF1744), "-", Color(0x66FF1744))
            }

            Box(
                modifier = Modifier
                    .size(220.dp)
                    .background(indicatorColor, shape = androidx.compose.foundation.shape.CircleShape),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = indicatorText,
                    color = if (polarityResult == PolarityResult.WAITING) Color.Gray else Color(0xFF121212),
                    fontSize = if (polarityResult == PolarityResult.WAITING) 24.sp else 120.sp,
                    fontWeight = FontWeight.Black
                )
            }
            
            Spacer(modifier = Modifier.height(48.dp))

            // --- Pulse Generator Card ---
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = Color(0xFF1E1E1E)),
                elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(text = stringResource(R.string.pulse_generator), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.LightGray)
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            // Play Button
                            IconButton(onClick = { viewModel.togglePlay() }) {
                                Icon(
                                    imageVector = Icons.Filled.PlayArrow,
                                    contentDescription = "Play",
                                    tint = if (isPlaying) Color(0xFF00E676) else Color.Gray,
                                    modifier = Modifier.size(36.dp)
                                )
                            }
                            Spacer(modifier = Modifier.width(8.dp))
                            // Invert Button
                            Surface(
                                shape = androidx.compose.foundation.shape.CircleShape,
                                color = if (isInverted) Color(0xFFFF1744) else Color.Transparent,
                                modifier = Modifier.clickable { viewModel.toggleInvert() }
                            ) {
                                Text(
                                    text = "Ø",
                                    fontSize = 24.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = if (isInverted) Color.White else Color.Gray,
                                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
                                )
                            }
                        }
                    }

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

                    // Frequencies Row
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        val frequencies = listOf("80Hz", "160Hz", "500Hz", "1k2Hz", "4kHz", "FR")
                        frequencies.forEach { freq ->
                            val isSelected = selectedFrequency == freq
                            Text(
                                text = freq,
                                fontSize = 16.sp,
                                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                                color = if (isSelected) Color(0xFF29B6F6) else Color.Gray,
                                modifier = Modifier.clickable { viewModel.setFrequency(freq) }
                            )
                        }
                    }
                }
            }

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

            // --- Analyzer Settings Card ---
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = Color(0xFF1E1E1E)),
                elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(text = stringResource(R.string.analyzer), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = Color.LightGray)
                        Text(text = stringResource(R.string.input_level, String.format("%.1f", inputLevel)), color = Color.Gray, fontSize = 14.sp)
                    }

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

                    // Segmented VU Meter
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(24.dp)
                    ) {
                        val numSegments = 30
                        Row(
                            modifier = Modifier.fillMaxSize(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            val levelPct = ((inputLevel + 60) / 60).coerceIn(0f, 1f)
                            val activeSegments = (levelPct * numSegments).toInt()
                            
                            for (i in 0 until numSegments) {
                                val isActive = i < activeSegments
                                val segmentColor = when {
                                    !isActive -> Color(0xFF2A2A2A)
                                    i > numSegments * 0.85 -> Color(0xFFFF1744) // Red
                                    i > numSegments * 0.6 -> Color(0xFFFFEA00)  // Yellow
                                    else -> Color(0xFF00E676)                   // Green
                                }
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxHeight()
                                        .padding(horizontal = 1.dp)
                                        .background(segmentColor)
                                )
                            }
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))

                    Slider(
                        value = threshold,
                        onValueChange = { viewModel.setThreshold(it) },
                        valueRange = -60f..0f,
                        colors = SliderDefaults.colors(
                            thumbColor = Color(0xFF29B6F6),
                            activeTrackColor = Color(0xFF29B6F6),
                            inactiveTrackColor = Color.DarkGray
                        )
                    )

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(text = stringResource(R.string.threshold_label), color = Color.Gray, fontSize = 12.sp)
                        Text(text = stringResource(R.string.threshold_value, String.format("%.1f", threshold)), color = Color(0xFF29B6F6), fontSize = 14.sp, fontWeight = FontWeight.Bold)
                    }
                    Text(
                        text = stringResource(R.string.threshold_hint),
                        color = Color.DarkGray,
                        fontSize = 11.sp,
                        modifier = Modifier.padding(top = 4.dp)
                    )
                }
            }

            Spacer(modifier = Modifier.weight(1f))

            // --- EM2 Events Footer ---
            Text(
                text = stringResource(R.string.footer_credit),
                color = Color.Gray,
                fontSize = 11.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(bottom = 16.dp)
            )
        }

        // Settings Icon (Top Right)
        IconButton(
            onClick = { showSettingsDialog = true },
            modifier = Modifier
                .align(Alignment.TopEnd)
                .padding(16.dp)
        ) {
            Icon(
                imageVector = Icons.Filled.Settings,
                contentDescription = stringResource(R.string.settings),
                tint = Color.Gray
            )
        }

        if (showSettingsDialog) {
            AlertDialog(
                onDismissRequest = { showSettingsDialog = false },
                title = { Text(text = stringResource(R.string.settings)) },
                text = {
                    Column {
                        Text(text = stringResource(R.string.language), fontWeight = FontWeight.Bold, modifier = Modifier.padding(bottom = 8.dp))
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags("en"))
                                    showSettingsDialog = false
                                }
                                .padding(vertical = 12.dp)
                        ) {
                            Text(text = "English")
                        }
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags("fr"))
                                    showSettingsDialog = false
                                }
                                .padding(vertical = 12.dp)
                        ) {
                            Text(text = "Français")
                        }
                    }
                },
                confirmButton = {
                    TextButton(onClick = { showSettingsDialog = false }) {
                        Text("OK")
                    }
                }
            )
        }
    }
}
