package eu.gaudian.translator.view.vocabulary.widgets

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.StrokeCap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.TagCategory
import eu.gaudian.translator.model.VocabularyCategory
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.ui.theme.semanticColors
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.SecondaryButton
import eu.gaudian.translator.viewmodel.ProgressViewModel

@Composable
fun CategoryProgressWidget(
    onCategoryClicked: (VocabularyCategory?) -> Unit,
    onViewAllClicked: () -> Unit
) {

    val activity = LocalContext.current.findActivity()
    val viewModel : ProgressViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val categoryProgressList by viewModel.categoryProgressList.collectAsState(initial = emptyList())
    val selectedCategories by viewModel.selectedCategories.collectAsState(initial = emptySet())

    var expanded by remember { mutableStateOf(false) }

        Column(
            modifier = Modifier.padding(16.dp).fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {


            ChartLegend()

            Row(
                modifier = Modifier
                    .height(200.dp)
                    .fillMaxWidth()
                    .horizontalScroll(rememberScrollState()),
                horizontalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                if (selectedCategories.isEmpty()) {
                    // Show all categories if none are selected
                    categoryProgressList.forEach { data ->
                        CategoryProgressCircle(
                            category = data.vocabularyCategory.name,
                            totalItems = data.totalItems,
                            itemsCompleted = data.itemsCompleted,
                            itemsInStages = data.itemsInStages,
                            newItems = data.newItems,
                            onClick = { onCategoryClicked(data.vocabularyCategory) },
                            showPercentage = true,
                            type = if(data.vocabularyCategory is TagCategory) CategoryCircleType.List else CategoryCircleType.Filter
                        )
                    }
                } else {
                    // Show only selected categories
                    selectedCategories.forEach { categoryId ->
                        val data = categoryProgressList.find { it.vocabularyCategory.id == categoryId }
                        if (data != null) {
                            CategoryProgressCircle(
                                category = data.vocabularyCategory.name,
                                totalItems = data.totalItems,
                                itemsCompleted = data.itemsCompleted,
                                itemsInStages = data.itemsInStages,
                                newItems = data.newItems,
                                onClick = { onCategoryClicked(data.vocabularyCategory) },
                                showPercentage = true,
                                type = if(data.vocabularyCategory is TagCategory) CategoryCircleType.List else CategoryCircleType.Filter
                            )
                        }
                    }
                }
            }
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally)
            ) {
                Box {
                    SecondaryButton(
                        onClick = { expanded = true },
                        text = stringResource(R.string.label_select),
                        icon = AppIcons.FilterFilled
                    )
                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false },
                        modifier = Modifier.background(MaterialTheme.colorScheme.surfaceContainer)
                    ) {
                        categoryProgressList.forEach { data ->
                            val isSelected = selectedCategories.contains(data.vocabularyCategory.id)
                            DropdownMenuItem(
                                text = { Text(text = data.vocabularyCategory.name) },
                                onClick = { viewModel.toggleCategorySelection(data.vocabularyCategory.id) },
                                leadingIcon = {
                                    Checkbox(
                                        checked = isSelected,
                                        onCheckedChange = { viewModel.toggleCategorySelection(data.vocabularyCategory.id) }
                                    )
                                }
                            )
                        }
                    }
                }

                SecondaryButton(
                    onClick = onViewAllClicked,
                    text = stringResource(id = R.string.label_all_categories),
                    icon = AppIcons.ArrowForward
                )
            }
        }
}

enum class CategoryCircleType { Filter, List }

@Composable
fun CategoryProgressCircle(
    category: String? = null,
    totalItems: Int,
    itemsCompleted: Int,
    itemsInStages: Int,
    newItems: Int,
    circleSize: Dp = 120.dp,
    onClick: (() -> Unit)? = null,
    showPercentage: Boolean = false,
    type: CategoryCircleType? = null
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(8.dp),
        modifier = if (onClick != null) {
            Modifier
                .clip(MaterialTheme.shapes.medium)
                .clickable { onClick() }
                .padding(8.dp)
        } else {
            Modifier
                .clip(MaterialTheme.shapes.medium)
                .padding(8.dp)
        }
    ) {
        if (category != null) {
            Text(
                text = category,
                style = MaterialTheme.typography.titleSmall
            )
        }

        when {
            totalItems == 0 -> {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier
                        .size(circleSize)
                        .background(MaterialTheme.colorScheme.surfaceContainerHighest, CircleShape).fillMaxWidth()
                ) {
                    Text(
                        modifier = Modifier.align(Alignment.Center).padding(4.dp).fillMaxWidth(),
                        text = stringResource(R.string.text_no_items_available),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    if (type != null) {
                        CategoryTypeBadge(type)
                    }
                }
            }
            itemsCompleted == totalItems -> {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.size(circleSize)
                ) {
                    Icon(
                        imageVector = AppIcons.CheckCircle,
                        contentDescription = stringResource(R.string.text_all_items_completed),
                        tint = MaterialTheme.semanticColors.stageGradient6,
                        modifier = Modifier.size(circleSize * 0.6f)
                    )
                    if (type != null) {
                        CategoryTypeBadge(type)
                    }
                }
            }
            else -> {
                val pCompleted = if (totalItems > 0) itemsCompleted.toFloat() / totalItems else 0f
                val pInStages = if (totalItems > 0) itemsInStages.toFloat() / totalItems else 0f
                val pNew = if (totalItems > 0) newItems.toFloat() / totalItems else 0f

                val animatedCompleted by animateFloatAsState(targetValue = pCompleted, animationSpec = tween(1000), label = "")
                val animatedInStages by animateFloatAsState(targetValue = pInStages, animationSpec = tween(1000), label = "")
                val animatedNew by animateFloatAsState(targetValue = pNew, animationSpec = tween(1000), label = "")

                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.size(circleSize)
                ) {
                    val strokeWidth = circleSize * 0.1f
                    // Background track
                    CircularProgressIndicator(
                        progress = { 1f },
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.colorScheme.surfaceVariant,
                        strokeWidth = strokeWidth,
                    )
                    // New Items
                    CircularProgressIndicator(
                        progress = { animatedNew + animatedInStages + animatedCompleted },
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.semanticColors.stageGradient1,
                        strokeWidth = strokeWidth,
                        strokeCap = StrokeCap.Round
                    )
                    // In Stages
                    CircularProgressIndicator(
                        progress = { animatedInStages + animatedCompleted },
                        modifier = Modifier.size(circleSize * 0.75f),
                        color = MaterialTheme.semanticColors.stageGradient3,
                        strokeWidth = strokeWidth,
                        strokeCap = StrokeCap.Round
                    )
                    // Completed
                    CircularProgressIndicator(
                        progress = { animatedCompleted },
                        modifier = Modifier.size(circleSize * 0.5f),
                        color = MaterialTheme.semanticColors.stageGradient6,
                        strokeWidth = strokeWidth,
                        strokeCap = StrokeCap.Round
                    )

                    if (showPercentage) {
                        Text(
                            text = "${(pCompleted * 100).toInt()}%",
                            style = MaterialTheme.typography.headlineSmall,
                        )
                    }
                    if (type != null) {
                        CategoryTypeBadge(type)
                    }
                }
            }
        }
        // NOTE: You may need to add a plural string resource for "items"
        Text(
            text = stringResource(R.string.items, totalItems),
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}
@Composable
private fun ChartLegend() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally)
    ) {
        LegendItem(color = MaterialTheme.semanticColors.stageGradient6, label = stringResource(R.string.label_done))
        LegendItem(color = MaterialTheme.semanticColors.stageGradient3, label = stringResource(R.string.label_in_stages))
        LegendItem(color = MaterialTheme.semanticColors.stageGradient1, label = stringResource(R.string.label_new))
    }
}

@Composable
private fun LegendItem(color: Color, label: String) {
    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
        Box(
            modifier = Modifier
                .size(10.dp)
                .background(color, shape = CircleShape)
        )
        Text(text = label, style = MaterialTheme.typography.labelMedium)
    }
}



@ThemePreviews
@Composable
private fun VocabularyStatsWidgetPreview() {
    LevelWidget(
        totalWords = 500, learnedWords = 150,
        onNavigateToProgress = {  }
    )
}

@Suppress("HardCodedStringLiteral")
@ThemePreviews
@Composable
private fun CategoryProgressCirclePreview() {
    Column(
        modifier = Modifier.padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        CategoryProgressCircle(category = "Greetings", totalItems = 100, itemsCompleted = 20, itemsInStages = 30, newItems = 50, showPercentage = true)
        CategoryProgressCircle(category = "Food", totalItems = 50, itemsCompleted = 50, itemsInStages = 0, newItems = 0)
        CategoryProgressCircle(category = "Empty", totalItems = 0, itemsCompleted = 0, itemsInStages = 0, newItems = 0)
    }
}


@Composable
private fun BoxScope.CategoryTypeBadge(type: CategoryCircleType) {
    val icon = when (type) {
        CategoryCircleType.Filter -> AppIcons.FilterCategory
        CategoryCircleType.List -> AppIcons.FilterList
    }
    val contentDesc = when (type) {
        CategoryCircleType.Filter -> stringResource(R.string.text_filter)
        CategoryCircleType.List -> stringResource(R.string.text_list)
    }
    Box(
        modifier = Modifier
            .align(Alignment.TopEnd)
            .padding(6.dp)
            .size(20.dp)
            .background(MaterialTheme.colorScheme.surface, CircleShape),
        contentAlignment = Alignment.Center
    ) {
        Icon(
            imageVector = icon,
            contentDescription = contentDesc,
            tint = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.size(12.dp)
        )
    }
}