package com.tt.honeyDue.ui.screens.task

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.ElectricBolt
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.Park
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.filled.Shield
import androidx.compose.material.icons.filled.Thermostat
import androidx.compose.material.icons.filled.Water
import androidx.compose.material.icons.filled.Weekend
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.models.TaskTemplate
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.components.common.StandardCard
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.util.ErrorMessageParser
import honeydue.composeapp.generated.resources.Res
import honeydue.composeapp.generated.resources.common_back
import honeydue.composeapp.generated.resources.templates_all_categories
import honeydue.composeapp.generated.resources.templates_apply_count
import honeydue.composeapp.generated.resources.templates_create_failed
import honeydue.composeapp.generated.resources.templates_empty_message
import honeydue.composeapp.generated.resources.templates_empty_title
import honeydue.composeapp.generated.resources.templates_load_failed
import honeydue.composeapp.generated.resources.templates_retry
import honeydue.composeapp.generated.resources.templates_selected_count
import honeydue.composeapp.generated.resources.templates_title
import org.jetbrains.compose.resources.stringResource

/**
 * Full-screen browser for backend task templates. Android port of iOS
 * `TaskTemplatesBrowserView`, extended with multi-select + bulk-create.
 *
 * Flow:
 *  1. Loads grouped templates via APILayer.getTaskTemplatesGrouped().
 *  2. User filters by category chip.
 *  3. User taps templates to toggle them into a selection set.
 *  4. Apply button triggers APILayer.bulkCreateTasks — each created task
 *     carries its originating templateId for reporting (per CLAUDE.md rule).
 *  5. Success fires analytics events and invokes [onCreated] with the count
 *     so the caller can navigate away or show a toast.
 *
 * [fromOnboarding]: flip to true when presenting inside the onboarding flow
 * so the onboarding-funnel PostHog events fire instead of the general
 * task_template_accepted / task_templates_bulk_created pair.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskTemplatesBrowserScreen(
    residenceId: Int,
    onNavigateBack: () -> Unit,
    onCreated: (createdCount: Int) -> Unit = { onNavigateBack() },
    fromOnboarding: Boolean = false,
    viewModel: TaskTemplatesBrowserViewModel = viewModel {
        TaskTemplatesBrowserViewModel(
            residenceId = residenceId,
            fromOnboarding = fromOnboarding
        )
    }
) {
    val templatesState by viewModel.templatesState.collectAsStateWithLifecycle()
    val selectedIds by viewModel.selectedTemplateIds.collectAsStateWithLifecycle()
    val selectedCategory by viewModel.selectedCategory.collectAsStateWithLifecycle()
    val applyState by viewModel.applyState.collectAsStateWithLifecycle()
    var isRefreshing by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        if (templatesState is ApiResult.Idle) {
            viewModel.load()
        }
    }

    // Exit when the bulk create succeeds. We keep the VM alive for one more
    // frame so the count-success state is visible, then pop back.
    LaunchedEffect(applyState) {
        if (applyState is ApiResult.Success) {
            val count = (applyState as ApiResult.Success<Int>).data
            onCreated(count)
            viewModel.resetApplyState()
        }
        if (templatesState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Column {
                        Text(
                            stringResource(Res.string.templates_title),
                            fontWeight = FontWeight.SemiBold
                        )
                        if (selectedIds.isNotEmpty()) {
                            Text(
                                stringResource(Res.string.templates_selected_count, selectedIds.size),
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = stringResource(Res.string.common_back)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        },
        bottomBar = {
            ApplyBar(
                selectedCount = selectedIds.size,
                applyState = applyState,
                onApply = { viewModel.apply() }
            )
        }
    ) { paddingValues ->
        PullToRefreshBox(
            isRefreshing = isRefreshing,
            onRefresh = {
                isRefreshing = true
                viewModel.load(forceRefresh = true)
            },
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            when (val state = templatesState) {
                is ApiResult.Loading, ApiResult.Idle -> {
                    Box(Modifier.fillMaxSize(), Alignment.Center) {
                        CircularProgressIndicator()
                    }
                }
                is ApiResult.Error -> {
                    LoadErrorView(
                        message = ErrorMessageParser.parse(state.message),
                        onRetry = { viewModel.load(forceRefresh = true) }
                    )
                }
                is ApiResult.Success -> {
                    if (state.data.categories.isEmpty()) {
                        EmptyState()
                    } else {
                        TemplatesList(
                            categories = viewModel.categoryNames,
                            selectedCategory = selectedCategory,
                            onCategorySelected = viewModel::selectCategory,
                            templates = viewModel.filteredTemplates(),
                            selectedIds = selectedIds,
                            onToggle = viewModel::toggleSelection
                        )
                    }
                }
            }

            // Overlay for apply errors so user can retry without losing selection.
            (applyState as? ApiResult.Error)?.let { err ->
                ApplyErrorBanner(
                    message = ErrorMessageParser.parse(err.message),
                    onDismiss = { viewModel.resetApplyState() }
                )
            }
        }
    }

    // Track screen impressions.
    LaunchedEffect(Unit) {
        // Re-use the generic screen event; specific accept/create events are
        // emitted inside the ViewModel when the user hits Apply.
        PostHogAnalytics.screen(
            if (fromOnboarding) AnalyticsEvents.ONBOARDING_SUGGESTIONS_LOADED
            else AnalyticsEvents.TASK_SCREEN_SHOWN
        )
    }
}

@Composable
private fun TemplatesList(
    categories: List<String>,
    selectedCategory: String?,
    onCategorySelected: (String?) -> Unit,
    templates: List<TaskTemplate>,
    selectedIds: Set<Int>,
    onToggle: (Int) -> Unit
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(
            start = AppSpacing.lg,
            end = AppSpacing.lg,
            top = AppSpacing.md,
            bottom = AppSpacing.xl
        ),
        verticalArrangement = Arrangement.spacedBy(AppSpacing.sm)
    ) {
        item("categories") {
            CategoryChipRow(
                categories = categories,
                selected = selectedCategory,
                onSelect = onCategorySelected
            )
        }

        if (templates.isEmpty()) {
            item("empty-for-category") {
                Box(
                    Modifier.fillMaxWidth().padding(AppSpacing.xl),
                    Alignment.Center
                ) {
                    Text(
                        text = stringResource(Res.string.templates_empty_message),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        } else {
            items(templates, key = { it.id }) { template ->
                TemplateCard(
                    template = template,
                    selected = template.id in selectedIds,
                    onToggle = { onToggle(template.id) }
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CategoryChipRow(
    categories: List<String>,
    selected: String?,
    onSelect: (String?) -> Unit
) {
    val scrollState = rememberScrollState()
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .horizontalScroll(scrollState),
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
    ) {
        FilterChip(
            selected = selected == null,
            onClick = { onSelect(null) },
            label = { Text(stringResource(Res.string.templates_all_categories)) }
        )
        categories.forEach { name ->
            FilterChip(
                selected = selected == name,
                onClick = { onSelect(name) },
                leadingIcon = {
                    Icon(
                        imageVector = categoryIconFor(name),
                        contentDescription = null, // decorative
                        modifier = Modifier.size(16.dp)
                    )
                },
                label = { Text(name) }
            )
        }
    }
}

@Composable
private fun TemplateCard(
    template: TaskTemplate,
    selected: Boolean,
    onToggle: () -> Unit
) {
    val containerColor =
        if (selected) MaterialTheme.colorScheme.primaryContainer
        else MaterialTheme.colorScheme.surface
    val borderColor =
        if (selected) MaterialTheme.colorScheme.primary
        else Color.Transparent

    StandardCard(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onToggle() },
        backgroundColor = containerColor,
        contentPadding = AppSpacing.md
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(AppSpacing.md),
            modifier = Modifier.fillMaxWidth()
        ) {
            // Category bubble
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(categoryBubbleColor(template.categoryName)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = categoryIconFor(template.categoryName),
                    contentDescription = null, // decorative
                    tint = Color.White,
                    modifier = Modifier.size(20.dp)
                )
            }

            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = template.title,
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.Medium,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                    color = MaterialTheme.colorScheme.onSurface
                )
                if (template.description.isNotBlank()) {
                    Text(
                        text = template.description,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    modifier = Modifier.padding(top = AppSpacing.xs)
                ) {
                    Text(
                        text = template.frequencyDisplay,
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    if (template.categoryName.isNotBlank() &&
                        template.categoryName != "Uncategorized"
                    ) {
                        Text(
                            text = "• ${template.categoryName}",
                            style = MaterialTheme.typography.labelMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }

            Icon(
                imageVector = if (selected) Icons.Default.CheckCircle
                else Icons.Default.RadioButtonUnchecked,
                contentDescription = if (selected) "Selected" else "Not selected",
                tint = if (selected) MaterialTheme.colorScheme.primary
                else MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier
                    .size(24.dp)
                    .background(borderColor.copy(alpha = 0f), CircleShape)
            )
        }
    }
}

@Composable
private fun ApplyBar(
    selectedCount: Int,
    applyState: ApiResult<Int>,
    onApply: () -> Unit
) {
    Surface(
        color = MaterialTheme.colorScheme.surface,
        tonalElevation = 6.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = AppSpacing.lg, vertical = AppSpacing.md),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(
                onClick = onApply,
                enabled = selectedCount > 0 && applyState !is ApiResult.Loading,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(52.dp),
                shape = RoundedCornerShape(AppRadius.md)
            ) {
                if (applyState is ApiResult.Loading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                } else {
                    Icon(Icons.Default.Check, contentDescription = null) // decorative
                    Spacer(Modifier.width(AppSpacing.sm))
                    Text(
                        text = stringResource(Res.string.templates_apply_count, selectedCount),
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    }
}

@Composable
private fun LoadErrorView(
    message: String,
    onRetry: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxSize().padding(AppSpacing.xl),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(AppSpacing.md, Alignment.CenterVertically)
    ) {
        Icon(
            imageVector = Icons.Default.ErrorOutline,
            contentDescription = "Error",
            modifier = Modifier.size(48.dp),
            tint = MaterialTheme.colorScheme.error
        )
        Text(
            text = stringResource(Res.string.templates_load_failed),
            style = MaterialTheme.typography.titleMedium
        )
        Text(
            text = message,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        OutlinedButton(onClick = onRetry) {
            Text(stringResource(Res.string.templates_retry))
        }
    }
}

@Composable
private fun EmptyState() {
    Column(
        modifier = Modifier.fillMaxSize().padding(AppSpacing.xl),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(AppSpacing.md, Alignment.CenterVertically)
    ) {
        Icon(
            imageVector = Icons.Default.Checklist,
            contentDescription = null, // decorative
            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
        )
        Text(
            text = stringResource(Res.string.templates_empty_message),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun BoxScope.ApplyErrorBanner(
    message: String,
    onDismiss: () -> Unit
) {
    Surface(
        modifier = Modifier
            .align(Alignment.BottomCenter)
            .padding(AppSpacing.lg)
            .clickable { onDismiss() },
        color = MaterialTheme.colorScheme.errorContainer,
        shape = RoundedCornerShape(AppRadius.md),
        tonalElevation = 4.dp
    ) {
        Row(
            modifier = Modifier.padding(AppSpacing.md),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
        ) {
            Icon(
                imageVector = Icons.Default.ErrorOutline,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.error
            )
            Column {
                Text(
                    text = stringResource(Res.string.templates_create_failed),
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.onErrorContainer
                )
                Text(
                    text = message,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onErrorContainer
                )
            }
        }
    }
}

// ---------- Category styling helpers ----------

private fun categoryIconFor(category: String): ImageVector =
    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.Bolt
    }

/** Explicit palette so the bubble contrasts on white/dark cards. Mirrors iOS Color.taskCategoryColor. */
private fun categoryBubbleColor(category: String): Color = when (category.lowercase()) {
    "plumbing" -> Color(0xFF0055A5)
    "safety" -> Color(0xFFDD1C1A)
    "electrical" -> Color(0xFFFFB300)
    "hvac" -> Color(0xFF07A0C3)
    "appliances" -> Color(0xFF7B1FA2)
    "exterior" -> Color(0xFF34C759)
    "lawn & garden" -> Color(0xFF2E7D32)
    "interior" -> Color(0xFFAF52DE)
    "general", "seasonal" -> Color(0xFFFF9500)
    else -> Color(0xFF455A64)
}
