package com.atridad.ascently.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.atridad.ascently.R
import com.atridad.ascently.data.model.Attempt
import com.atridad.ascently.data.model.AttemptResult
import com.atridad.ascently.data.model.ClimbType
import com.atridad.ascently.data.model.Gym
import com.atridad.ascently.data.model.Problem
import com.atridad.ascently.ui.components.SyncIndicator
import com.atridad.ascently.ui.viewmodel.ClimbViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String) -> Unit) {
    val problems by viewModel.problems.collectAsState()
    val gyms by viewModel.gyms.collectAsState()
    val attempts by viewModel.attempts.collectAsState()

    // Filter state
    var selectedClimbType by remember { mutableStateOf<ClimbType?>(null) }
    var selectedGym by remember { mutableStateOf<Gym?>(null) }

    // Apply filters
    val filteredProblems = remember(problems, selectedClimbType, selectedGym) {
        problems.filter { problem ->
            val climbTypeMatch = selectedClimbType?.let { it == problem.climbType } != false
            val gymMatch = selectedGym?.let { it.id == problem.gymId } != false
            climbTypeMatch && gymMatch
        }
    }

    // Separate active and inactive problems
    val activeProblems = remember(filteredProblems) { filteredProblems.filter { it.isActive } }
    val inactiveProblems = remember(filteredProblems) { filteredProblems.filter { !it.isActive } }
    val sortedProblems = remember(activeProblems, inactiveProblems) { activeProblems + inactiveProblems }

    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Icon(
                painter = painterResource(id = R.drawable.ic_mountains),
                contentDescription = "Ascently Logo",
                modifier = Modifier.size(32.dp),
                tint = MaterialTheme.colorScheme.primary,
            )
            Text(
                text = "Climbing Problems",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.weight(1f),
            )
            SyncIndicator(isSyncing = viewModel.syncService.isSyncing)
        }

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

        // Filters Section
        if (problems.isNotEmpty()) {
            Card(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "Filters",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                    )

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

                    // Climb Type Filter
                    Text(
                        text = "Climb Type",
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium,
                    )

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

                    LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        item {
                            FilterChip(
                                onClick = { selectedClimbType = null },
                                label = { Text("All Types") },
                                selected = selectedClimbType == null,
                            )
                        }
                        items(ClimbType.entries) { climbType ->
                            FilterChip(
                                onClick = { selectedClimbType = climbType },
                                label = { Text(climbType.displayName) },
                                selected = selectedClimbType == climbType,
                            )
                        }
                    }

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

                    // Gym Filter
                    Text(
                        text = "Gym",
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium,
                    )

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

                    LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        item {
                            FilterChip(
                                onClick = { selectedGym = null },
                                label = { Text("All Gyms") },
                                selected = selectedGym == null,
                            )
                        }
                        items(gyms) { gym ->
                            FilterChip(
                                onClick = { selectedGym = gym },
                                label = { Text(gym.name) },
                                selected = selectedGym?.id == gym.id,
                            )
                        }
                    }

                    // Filter result count
                    if (selectedClimbType != null || selectedGym != null) {
                        Spacer(modifier = Modifier.height(12.dp))
                        Text(
                            text =
                            "Showing ${filteredProblems.size} of ${problems.size} problems (${activeProblems.size} active, ${inactiveProblems.size} reset)",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                }
            }

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

        if (filteredProblems.isEmpty()) {
            EmptyStateMessage(
                title =
                if (problems.isEmpty()) {
                    if (gyms.isEmpty()) "No Gyms Available" else "No Problems Yet"
                } else {
                    "No Problems Match Filters"
                },
                message =
                if (problems.isEmpty()) {
                    if (gyms.isEmpty()) {
                        "Add a gym first to start tracking problems and routes!"
                    } else {
                        "Start tracking your favorite problems and routes!"
                    }
                } else {
                    "Try adjusting your filters to see more problems."
                },
                onActionClick = {},
                actionText = "",
            )
        } else {
            LazyColumn {
                    items(sortedProblems, key = { it.id }) { problem ->
                    ProblemCard(
                        problem = problem,
                        gymName = gyms.find { it.id == problem.gymId }?.name ?: "Unknown Gym",
                        attempts = attempts,
                        onClick = { onNavigateToProblemDetail(problem.id) },
                        onToggleActive = {
                            val updatedProblem = problem.copy(isActive = !problem.isActive)
                            viewModel.updateProblem(updatedProblem)
                        },
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProblemCard(
    problem: Problem,
    gymName: String,
    attempts: List<Attempt>,
    onClick: () -> Unit,
    onToggleActive: (() -> Unit)? = null,
) {
    val isCompleted =
        attempts.any { attempt ->
            attempt.problemId == problem.id &&
                (
                    attempt.result == AttemptResult.SUCCESS ||
                        attempt.result == AttemptResult.FLASH
                    )
        }

    Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top,
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = problem.name ?: "Unnamed Problem",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color =
                        if (problem.isActive) {
                            MaterialTheme.colorScheme.onSurface
                        } else {
                            MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                        },
                    )

                    Text(
                        text = gymName,
                        style = MaterialTheme.typography.bodyMedium,
                        color =
                        MaterialTheme.colorScheme.onSurfaceVariant.copy(
                            alpha = if (problem.isActive) 1f else 0.6f,
                        ),
                    )
                }

                Column(horizontalAlignment = Alignment.End) {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        if (problem.imagePaths.isNotEmpty()) {
                            Icon(
                                imageVector = Icons.Default.Image,
                                contentDescription = "Has images",
                                modifier = Modifier.size(16.dp),
                                tint = MaterialTheme.colorScheme.primary,
                            )
                        }

                        if (isCompleted) {
                            Icon(
                                imageVector = Icons.Default.CheckCircle,
                                contentDescription = "Completed",
                                modifier = Modifier.size(16.dp),
                                tint = MaterialTheme.colorScheme.tertiary,
                            )
                        }

                        Text(
                            text = problem.difficulty.grade,
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary,
                        )
                    }

                    Text(
                        text = problem.climbType.displayName,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }

            problem.location?.let { location ->
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "Location: $location",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }

            if (problem.tags.isNotEmpty()) {
                Spacer(modifier = Modifier.height(8.dp))
                Row {
                    problem.tags.take(3).forEach { tag ->
                        AssistChip(
                            onClick = {},
                            label = { Text(tag) },
                            modifier = Modifier.padding(end = 4.dp),
                        )
                    }
                }
            }

            if (!problem.isActive) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Reset / No Longer Set",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.tertiary,
                    fontWeight = FontWeight.Medium,
                )
            }

            // Toggle active button
            if (onToggleActive != null) {
                Spacer(modifier = Modifier.height(8.dp))
                OutlinedButton(
                    onClick = onToggleActive,
                    colors =
                    ButtonDefaults.outlinedButtonColors(
                        contentColor =
                        if (problem.isActive) {
                            MaterialTheme.colorScheme.tertiary
                        } else {
                            MaterialTheme.colorScheme.primary
                        },
                    ),
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text(
                        text = if (problem.isActive) "Mark as Reset" else "Mark as Active",
                        style = MaterialTheme.typography.bodySmall,
                    )
                }
            }
        }
    }
}
