package com.tt.honeyDue.ui.components

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.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.style.TextOverflow
import androidx.compose.ui.unit.dp
import honeydue.composeapp.generated.resources.*
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.models.TaskTemplate
import com.tt.honeyDue.models.TaskTemplateCategoryGroup
import org.jetbrains.compose.resources.stringResource

/**
 * Bottom sheet for browsing all task templates from backend.
 * Uses DataManager to access cached templates.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskTemplatesBrowserSheet(
    onDismiss: () -> Unit,
    onSelect: (TaskTemplate) -> Unit
) {
    var searchText by remember { mutableStateOf("") }
    var expandedCategories by remember { mutableStateOf(setOf<String>()) }

    // Get templates from DataManager
    val groupedTemplates by DataManager.taskTemplatesGrouped.collectAsState()
    val allTemplates by DataManager.taskTemplates.collectAsState()

    val filteredTemplates = remember(searchText, allTemplates) {
        if (searchText.isBlank()) emptyList()
        else DataManager.searchTaskTemplates(searchText)
    }

    val isSearching = searchText.isNotBlank()

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.9f)
        ) {
            // Header
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(Res.string.templates_title),
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold
                )
                TextButton(onClick = onDismiss) {
                    Text(stringResource(Res.string.templates_done))
                }
            }

            // Search bar
            OutlinedTextField(
                value = searchText,
                onValueChange = { searchText = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                placeholder = { Text(stringResource(Res.string.templates_search_placeholder)) },
                leadingIcon = {
                    Icon(Icons.Default.Search, contentDescription = null)
                },
                trailingIcon = {
                    if (searchText.isNotEmpty()) {
                        IconButton(onClick = { searchText = "" }) {
                            Icon(Icons.Default.Clear, contentDescription = stringResource(Res.string.templates_clear))
                        }
                    }
                },
                singleLine = true
            )

            HorizontalDivider()

            // Content
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(bottom = 32.dp)
            ) {
                if (isSearching) {
                    // Search results
                    if (filteredTemplates.isEmpty()) {
                        item {
                            EmptySearchState()
                        }
                    } else {
                        item {
                            val resultsText = if (filteredTemplates.size == 1) {
                                stringResource(Res.string.templates_result)
                            } else {
                                stringResource(Res.string.templates_results)
                            }
                            Text(
                                text = "${filteredTemplates.size} $resultsText",
                                style = MaterialTheme.typography.labelMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                modifier = Modifier.padding(16.dp)
                            )
                        }
                        items(filteredTemplates, key = { it.id }) { template ->
                            TaskTemplateItem(
                                template = template,
                                onClick = {
                                    onSelect(template)
                                    onDismiss()
                                }
                            )
                        }
                    }
                } else {
                    // Browse by category
                    val categories = groupedTemplates?.categories ?: emptyList()

                    if (categories.isEmpty()) {
                        item {
                            EmptyTemplatesState()
                        }
                    } else {
                        categories.forEach { categoryGroup ->
                            val categoryKey = categoryGroup.categoryName
                            val isExpanded = expandedCategories.contains(categoryKey)

                            item(key = "category_$categoryKey") {
                                CategoryHeader(
                                    categoryGroup = categoryGroup,
                                    isExpanded = isExpanded,
                                    onClick = {
                                        expandedCategories = if (isExpanded) {
                                            expandedCategories - categoryKey
                                        } else {
                                            expandedCategories + categoryKey
                                        }
                                    }
                                )
                            }

                            if (isExpanded) {
                                items(categoryGroup.templates, key = { it.id }) { template ->
                                    TaskTemplateItem(
                                        template = template,
                                        onClick = {
                                            onSelect(template)
                                            onDismiss()
                                        },
                                        modifier = Modifier.padding(start = 16.dp)
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun CategoryHeader(
    categoryGroup: TaskTemplateCategoryGroup,
    isExpanded: Boolean,
    onClick: () -> Unit
) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
        color = MaterialTheme.colorScheme.surface
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // Category icon
            Surface(
                modifier = Modifier.size(32.dp),
                shape = MaterialTheme.shapes.small,
                color = getCategoryColor(categoryGroup.categoryName.lowercase())
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        imageVector = getCategoryIcon(categoryGroup.categoryName.lowercase()),
                        contentDescription = null,
                        modifier = Modifier.size(18.dp),
                        tint = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }

            // Category name
            Text(
                text = categoryGroup.categoryName,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                modifier = Modifier.weight(1f)
            )

            // Count badge
            Surface(
                shape = MaterialTheme.shapes.small,
                color = MaterialTheme.colorScheme.surfaceVariant
            ) {
                Text(
                    text = categoryGroup.count.toString(),
                    style = MaterialTheme.typography.labelSmall,
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }

            // Expand/collapse indicator
            Icon(
                imageVector = if (isExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun TaskTemplateItem(
    template: TaskTemplate,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
        color = MaterialTheme.colorScheme.surface
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // Icon placeholder
            Surface(
                modifier = Modifier.size(24.dp),
                shape = MaterialTheme.shapes.extraSmall,
                color = getCategoryColor(template.categoryName.lowercase()).copy(alpha = 0.2f)
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Text(
                        text = template.title.first().toString(),
                        style = MaterialTheme.typography.labelSmall,
                        color = getCategoryColor(template.categoryName.lowercase())
                    )
                }
            }

            // Task info
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(2.dp)
            ) {
                Text(
                    text = template.title,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = template.frequencyDisplay,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            // Add indicator
            Icon(
                imageVector = Icons.Default.AddCircleOutline,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary
            )
        }
    }
}

@Composable
private fun EmptySearchState() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 48.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Icon(
            imageVector = Icons.Default.Search,
            contentDescription = null,
            modifier = Modifier.size(48.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
        )
        Text(
            text = stringResource(Res.string.templates_no_results_title),
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.onSurface
        )
        Text(
            text = stringResource(Res.string.templates_no_results_message),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun EmptyTemplatesState() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 48.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Icon(
            imageVector = Icons.Default.Checklist,
            contentDescription = null,
            modifier = Modifier.size(48.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
        )
        Text(
            text = stringResource(Res.string.templates_empty_title),
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.onSurface
        )
        Text(
            text = stringResource(Res.string.templates_empty_message),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun getCategoryIcon(category: String): androidx.compose.ui.graphics.vector.ImageVector {
    return when (category.lowercase()) {
        "plumbing" -> Icons.Default.Water
        "safety" -> Icons.Default.Shield
        "electrical" -> Icons.Default.ElectricBolt
        "hvac" -> Icons.Default.Thermostat
        "appliances" -> Icons.Default.Kitchen
        "exterior" -> Icons.Default.Home
        "lawn & garden" -> Icons.Default.Park
        "interior" -> Icons.Default.Weekend
        "general", "seasonal" -> Icons.Default.CalendarMonth
        else -> Icons.Default.Checklist
    }
}
