package com.manalejandro.odb2bluetooth.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import com.manalejandro.odb2bluetooth.ui.components.WarningDialog
import com.manalejandro.odb2bluetooth.ui.viewmodel.CommandResult
import com.manalejandro.odb2bluetooth.ui.viewmodel.MainViewModel
import java.text.SimpleDateFormat
import java.util.*

/**
 * Custom command screen - Send custom OBD2 commands
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CustomCommandScreen(
    viewModel: MainViewModel,
    onNavigateBack: () -> Unit
) {
    var commandText by remember { mutableStateOf("") }
    var editedCommand by remember { mutableStateOf("") }
    var showWarning by remember { mutableStateOf(false) }
    val commandHistory by viewModel.commandHistory.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()

    if (showWarning) {
        WarningDialog(
            onDismiss = {
                showWarning = false
                editedCommand = ""
            },
            onAccept = {
                showWarning = false
                viewModel.sendCommand(editedCommand)
                commandText = ""
                editedCommand = ""
            },
            title = "⚠️ DANGER - Read Carefully",
            message = "YOU ARE ABOUT TO SEND A CUSTOM COMMAND TO YOUR VEHICLE.\n\n" +
                    "Command: $editedCommand\n\n" +
                    "⚠️ WARNING:\n" +
                    "• Sending incorrect commands can DAMAGE your vehicle\n" +
                    "• You are FULLY RESPONSIBLE for any consequences\n" +
                    "• This action may VOID your warranty\n" +
                    "• Only proceed if you KNOW what this command does\n\n" +
                    "Do you accept ALL RISKS and want to proceed?"
        )
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Custom Commands") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(onClick = { viewModel.clearHistory() }) {
                        Icon(Icons.Default.Delete, contentDescription = "Clear history")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // Warning card
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Row(
                    modifier = Modifier.padding(16.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Warning,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.error
                    )
                    Column {
                        Text(
                            text = "⚠️ DANGER ZONE",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onErrorContainer
                        )
                        Text(
                            text = "Custom commands can damage your vehicle. Use ONLY if you know what you're doing. YOU are responsible for any consequences.",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onErrorContainer
                        )
                    }
                }
            }

            // Command input
            Column(
                modifier = Modifier.padding(horizontal = 16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                OutlinedTextField(
                    value = commandText,
                    onValueChange = { commandText = it.uppercase() },
                    label = { Text("OBD2 Command") },
                    placeholder = { Text("e.g., 010C, ATZ, 0105") },
                    leadingIcon = {
                        Icon(Icons.Default.Settings, contentDescription = null)
                    },
                    trailingIcon = {
                        if (commandText.isNotEmpty()) {
                            IconButton(onClick = { commandText = "" }) {
                                Icon(Icons.Default.Clear, contentDescription = "Clear")
                            }
                        }
                    },
                    keyboardOptions = KeyboardOptions(
                        capitalization = KeyboardCapitalization.Characters,
                        imeAction = ImeAction.Send
                    ),
                    keyboardActions = KeyboardActions(
                        onSend = {
                            if (commandText.isNotBlank()) {
                                editedCommand = commandText
                                showWarning = true
                            }
                        }
                    ),
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )

                Button(
                    onClick = {
                        if (commandText.isNotBlank()) {
                            editedCommand = commandText
                            showWarning = true
                        }
                    },
                    modifier = Modifier.fillMaxWidth(),
                    enabled = commandText.isNotBlank() && !isLoading,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Icon(Icons.Default.Send, contentDescription = null)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("Send Command")
                }
            }

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

            // Loading indicator
            if (isLoading) {
                LinearProgressIndicator(
                    modifier = Modifier.fillMaxWidth()
                )
            }

            // Common commands
            Text(
                text = "Common Commands",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(horizontal = 16.dp)
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                listOf("010C", "010D", "0105", "ATZ").forEach { cmd ->
                    FilterChip(
                        selected = false,
                        onClick = { commandText = cmd },
                        label = { Text(cmd) }
                    )
                }
            }

            Divider(modifier = Modifier.padding(vertical = 8.dp))

            // Command history
            Text(
                text = "Response History",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(horizontal = 16.dp)
            )

            if (commandHistory.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(32.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = null,
                            modifier = Modifier.size(64.dp),
                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "No commands sent yet",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            } else {
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(commandHistory) { result ->
                        CommandResultCard(
                            result = result,
                            onResend = {
                                commandText = result.command
                            }
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun CommandResultCard(
    result: CommandResult,
    onResend: () -> Unit
) {
    val dateFormat = remember { SimpleDateFormat("HH:mm:ss", Locale.getDefault()) }
    val isError = result.parsedResponse.contains("Error", ignoreCase = true) ||
                  result.rawResponse.contains("NO DATA", ignoreCase = true) ||
                  result.rawResponse.contains("ERROR", ignoreCase = true)

    ElevatedCard(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if (isError) {
                        Icon(
                            imageVector = Icons.Default.Warning,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.error,
                            modifier = Modifier.size(20.dp)
                        )
                    }
                    Text(
                        text = result.command,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                    )
                }
                IconButton(
                    onClick = onResend,
                    modifier = Modifier.size(32.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Refresh,
                        contentDescription = "Resend",
                        modifier = Modifier.size(20.dp)
                    )
                }
            }

            Divider()

            Text(
                text = "Response:",
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

            Surface(
                shape = MaterialTheme.shapes.small,
                color = MaterialTheme.colorScheme.surfaceVariant
            ) {
                Text(
                    text = result.rawResponse.ifBlank { "No response" },
                    style = MaterialTheme.typography.bodyMedium,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    modifier = Modifier.padding(8.dp)
                )
            }

            if (result.parsedResponse != result.rawResponse && result.parsedResponse.isNotBlank()) {
                Text(
                    text = "Parsed: ${result.parsedResponse}",
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium,
                    color = if (isError)
                        MaterialTheme.colorScheme.error
                    else
                        MaterialTheme.colorScheme.primary
                )
            }

            Text(
                text = dateFormat.format(Date(result.timestamp)),
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

