package com.optix.android.ui.components

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.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.optix.android.domain.model.ToolCategory
import com.optix.android.domain.model.ToolMetadata
import com.optix.android.ui.theme.*

@Composable
fun ToolPickerSheet(
    toolsByCategory: Map<ToolCategory, List<ToolMetadata>>,
    selectedTool: ToolMetadata?,
    favorites: Set<String>,
    onToolSelected: (ToolMetadata) -> Unit,
    onToggleFavorite: (String) -> Unit,
) {
    var searchQuery by remember { mutableStateOf("") }
    var selectedEnvFilter by remember { mutableStateOf("ALL") }

    val filteredTools = toolsByCategory.mapValues { (_, tools) ->
        tools.filter { tool ->
            val matchesQuery = tool.displayName.contains(searchQuery, ignoreCase = true) || 
                tool.description.contains(searchQuery, ignoreCase = true) ||
                tool.name.contains(searchQuery, ignoreCase = true)

            val matchesEnv = when (selectedEnvFilter) {
                "NATIVE" -> !tool.requiresTermux && !tool.requiresRoot
                "TERMUX" -> tool.requiresTermux
                "ROOT" -> tool.requiresRoot
                else -> true
            }

            matchesQuery && matchesEnv
        }
    }.filterValues { it.isNotEmpty() }

    Column(modifier = Modifier.padding(horizontal = 16.dp)) {
        OutlinedTextField(
            value = searchQuery,
            onValueChange = { searchQuery = it },
            placeholder = { Text("Search tools...", color = T.onSurfaceMid) },
            modifier = Modifier.fillMaxWidth().padding(top = 8.dp, bottom = 4.dp),
            leadingIcon = { Icon(Icons.Default.Search, null, tint = T.onSurfaceMid) },
            singleLine = true,
            shape = RoundedCornerShape(8.dp),
            colors = neonTextFieldColors()
        )

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 6.dp),
            horizontalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            listOf("ALL", "NATIVE", "TERMUX", "ROOT").forEach { env ->
                val selected = selectedEnvFilter == env
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .background(
                            if (selected) T.accent.copy(alpha = 0.16f) else T.surfaceVar.copy(alpha = 0.6f),
                            RoundedCornerShape(6.dp)
                        )
                        .border(
                            1.dp,
                            if (selected) T.accent.copy(alpha = 0.5f) else T.border.copy(alpha = 0.3f),
                            RoundedCornerShape(6.dp)
                        )
                        .clickable { selectedEnvFilter = env }
                        .padding(vertical = 6.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        env,
                        color = if (selected) T.accent else T.onSurfaceMid,
                        style = MaterialTheme.typography.labelSmall
                    )
                }
            }
        }

        LazyColumn(
            contentPadding = PaddingValues(bottom = 16.dp),
            verticalArrangement = Arrangement.spacedBy(4.dp),
        ) {
            val favoriteTools = toolsByCategory.values.flatten().filter { it.name in favorites && (searchQuery.isEmpty() || it.displayName.contains(searchQuery, true)) }
            if (favoriteTools.isNotEmpty()) {
                item {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(vertical = 8.dp),
                    ) {
                        Icon(Icons.Default.Star, null, tint = T.warning, modifier = Modifier.size(16.dp))
                        Spacer(Modifier.width(8.dp))
                        Text("Favorites", color = T.warning, style = MaterialTheme.typography.titleSmall)
                    }
                }
                items(favoriteTools, key = { "fav_${it.name}" }) { tool ->
                    ToolRow(
                        tool = tool,
                        isSelected = tool.name == selectedTool?.name,
                        isFavorite = true,
                        onToolSelected = onToolSelected,
                        onToggleFavorite = onToggleFavorite
                    )
                }
                item { Spacer(Modifier.height(8.dp)) }
            }

            filteredTools.forEach { (category, tools) ->
                item {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(vertical = 8.dp),
                    ) {
                        Box(Modifier.width(3.dp).height(16.dp).background(categoryColor(category), RoundedCornerShape(2.dp)))
                        Spacer(Modifier.width(8.dp))
                        Text(category.displayName, color = categoryColor(category), style = MaterialTheme.typography.titleSmall)
                    }
                }
                items(tools, key = { it.name }) { tool ->
                    ToolRow(
                        tool = tool,
                        isSelected = tool.name == selectedTool?.name,
                        isFavorite = tool.name in favorites,
                        onToolSelected = onToolSelected,
                        onToggleFavorite = onToggleFavorite
                    )
                }
            }
        }
    }
}

@Composable
private fun ToolRow(
    tool: ToolMetadata,
    isSelected: Boolean,
    isFavorite: Boolean,
    onToolSelected: (ToolMetadata) -> Unit,
    onToggleFavorite: (String) -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                if (isSelected) T.accent.copy(alpha = 0.12f) else T.surfaceVar.copy(alpha = 0.4f),
                RoundedCornerShape(6.dp),
            )
            .border(1.dp, if (isSelected) T.accent.copy(alpha = 0.4f) else T.border.copy(alpha = 0.3f), RoundedCornerShape(6.dp))
            .clickable { onToolSelected(tool) }
            .padding(horizontal = 12.dp, vertical = 10.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column(Modifier.weight(1f)) {
            Text(tool.displayName, color = T.onSurface, style = MaterialTheme.typography.bodyMedium)
            Text(tool.description.take(55), color = T.onSurfaceMid, style = MaterialTheme.typography.bodySmall)
        }
        
        Row(verticalAlignment = Alignment.CenterVertically) {
            if (tool.requiresRoot) {
                Text("ROOT", color = T.warning, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(end = 8.dp))
            }
            IconButton(onClick = { onToggleFavorite(tool.name) }, modifier = Modifier.size(24.dp)) {
                Icon(
                    imageVector = if (isFavorite) Icons.Default.Star else Icons.Default.StarBorder,
                    contentDescription = null,
                    tint = if (isFavorite) T.warning else T.onSurfaceMid,
                    modifier = Modifier.size(18.dp)
                )
            }
        }
    }
}

@Composable
private fun categoryColor(category: ToolCategory) = when (category) {
    ToolCategory.NETWORK_SCANNING    -> T.accent
    ToolCategory.DNS_WEB             -> T.warning
    ToolCategory.EXPLOITATION        -> T.exploit
    ToolCategory.PAYLOADS_UTILITIES  -> T.utility
    ToolCategory.LPE                 -> T.exploit
    ToolCategory.LATERAL_MOVEMENT    -> T.exploit
    ToolCategory.OSINT               -> T.accent
    ToolCategory.AI_REDTEAM          -> T.exploit
    ToolCategory.CLOUD_SEC           -> T.utility
    ToolCategory.CONTAINER_SEC       -> T.utility
    ToolCategory.THREAT_INTEL        -> T.accent
}

