package com.optix.android.ui.screens.settings

import android.app.Activity
import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.optix.android.data.repository.SettingsRepositoryImpl
import com.optix.android.ui.theme.*
import kotlinx.coroutines.launch

@Composable
fun ThemePickerSheet(settingsRepository: SettingsRepositoryImpl) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    
    val currentIsDark by settingsRepository.isDarkTheme().collectAsState(initial = true)
    val currentAccentId by settingsRepository.getAccentId().collectAsState(initial = "red")
    
    var pendingAccentId by remember { mutableStateOf<String?>(null) }
    var pendingIsDark by remember { mutableStateOf<Boolean?>(null) }
    var showConfirm by remember { mutableStateOf(false) }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        Text("THEME SYSTEM", color = T.accent, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)

        // ── Light/Dark Toggle ────────────────────────────────────────────────
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(T.surfaceVar.copy(alpha = 0.5f), RoundedCornerShape(12.dp))
                .padding(4.dp),
            horizontalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            val modes = listOf(true to "DARK", false to "LIGHT")
            modes.forEach { (isDark, label) ->
                val selected = currentIsDark == isDark
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .height(40.dp)
                        .background(
                            if (selected) T.accent else Color.Transparent,
                            RoundedCornerShape(8.dp)
                        )
                        .clickable {
                            if (!selected) {
                                pendingIsDark = isDark
                                pendingAccentId = currentAccentId
                                showConfirm = true
                            }
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        Icon(
                            if (isDark) Icons.Default.DarkMode else Icons.Default.LightMode,
                            null,
                            tint = if (selected) (if (T.isDark) Color.Black else Color.White) else T.onSurfaceMid,
                            modifier = Modifier.size(16.dp)
                        )
                        Text(
                            label,
                            color = if (selected) (if (T.isDark) Color.Black else Color.White) else T.onSurfaceMid,
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }

        // ── Accent Color Choice ──────────────────────────────────────────────
        Text("COLOR SCHEME", color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
        
        val accentOptions = listOf(
            "red"    to listOf(Color(0xFFFF1744)),
            "blue"   to listOf(Color(0xFF00E5FF)),
            "green"  to listOf(Color(0xFF00FF41)),
            "purple" to listOf(Color(0xFFBB66FF)),
            "orange" to listOf(Color(0xFFFFAB40)),
            "duo1"   to listOf(Color(0xFF00E5FF), Color(0xFFFF00FF)),
            "duo2"   to listOf(Color(0xFFCCFF00), Color(0xFFFF6D00)),
            "tri1"   to listOf(Color(0xFFFFD600), Color(0xFF7B1FA2), Color(0xFFFF1744)),
            "tri2"   to listOf(Color(0xFF00FF41), Color(0xFFFFAB40), Color(0xFF00E676)),
            "stealth" to listOf(Color(0xFF888888)),
            "cyberpunk" to listOf(Color(0xFF00F0FF), Color(0xFFFF007F), Color(0xFFFCEE09)),
            "nordic"  to listOf(Color(0xFF88C0D0), Color(0xFF8FBCBB), Color(0xFF5E81AC)),
            "sunset"  to listOf(Color(0xFFFF7E5F), Color(0xFFFEB47B), Color(0xFF7B1FA2)),
            "emerald" to listOf(Color(0xFF50C878)),
        )

        LazyVerticalGrid(
            columns = GridCells.Fixed(4),
            modifier = Modifier.height(240.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            items(accentOptions) { (id, colors) ->
                val selected = currentAccentId == id
                val primaryColor = colors.first()
                
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(6.dp),
                    modifier = Modifier.clickable {
                        if (!selected) {
                            pendingAccentId = id
                            pendingIsDark = currentIsDark
                            showConfirm = true
                        }
                    }
                ) {
                    Box(
                        modifier = Modifier
                            .size(48.dp)
                            .background(primaryColor.copy(alpha = 0.1f), CircleShape)
                            .border(
                                width = if (selected) 2.dp else 1.dp,
                                color = if (selected) primaryColor else T.border,
                                shape = CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Box(
                            modifier = Modifier
                                .size(24.dp)
                                .background(
                                    if (colors.size > 1) Brush.linearGradient(colors) 
                                    else SolidColor(primaryColor), 
                                    CircleShape
                                )
                        )
                    }
                    Text(
                        id.uppercase(),
                        color = if (selected) T.onSurface else T.onSurfaceMid,
                        style = MaterialTheme.typography.labelSmall,
                        textAlign = TextAlign.Center
                    )
                }
            }
        }

        Spacer(Modifier.height(16.dp))
    }

    // ── Restart Confirmation Dialog ──────────────────────────────────────────
    if (showConfirm) {
        AlertDialog(
            onDismissRequest = { showConfirm = false },
            containerColor = T.surface,
            shape = RoundedCornerShape(12.dp),
            title = {
                Text("APPLY THEME", color = T.accent, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
            },
            text = {
                Text(
                    "A restart is required to apply the global theme changes. Proceed?",
                    color = T.onSurface,
                    style = MaterialTheme.typography.bodyMedium
                )
            },
            confirmButton = {
                Button(
                    onClick = {
                        scope.launch {
                            val accent = pendingAccentId ?: currentAccentId
                            val dark = pendingIsDark ?: currentIsDark
                            settingsRepository.saveThemeConfig(dark, accent)
                            
                            // Restart Application
                            val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
                            intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                            context.startActivity(intent)
                            (context as? Activity)?.finish()
                        }
                    },
                    colors = ButtonDefaults.buttonColors(containerColor = T.accent, contentColor = if (T.isDark) Color.Black else Color.White),
                    shape = RoundedCornerShape(4.dp)
                ) {
                    Text("PROCEED")
                }
            },
            dismissButton = {
                TextButton(onClick = { showConfirm = false }) {
                    Text("CANCEL", color = T.onSurfaceMid)
                }
            }
        )
    }
}
