@file:Suppress("HardCodedStringLiteral")

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.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.ui.theme.semanticColors
import eu.gaudian.translator.viewmodel.WeeklyActivityStat
import kotlinx.coroutines.delay

/**
 * A widget that displays weekly activity statistics in a visually appealing bar chart.
 * It's designed to be consistent with the app's modern, floating UI style.
 *
 * @param weeklyStats A list of [WeeklyActivityStat] for the last 7 days.
 */
@Composable
fun WeeklyActivityChartWidget(
    weeklyStats: List<WeeklyActivityStat>
) {
    val maxValue = remember(weeklyStats) {
        (weeklyStats.flatMap { listOf(it.newlyAdded, it.completed, it.answeredRight) }.maxOrNull() ?: 0).let {
            if (it < 10) 10 else ((it / 5) + 1) * 5
        }
    }

    val hasNoData = remember(weeklyStats) {
        weeklyStats.all { it.newlyAdded == 0 && it.completed == 0 && it.answeredRight == 0 }
    }

    if (hasNoData) {
        Box(
            modifier = Modifier
                .fillMaxWidth(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = stringResource(R.string.text_no_data_available),
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    } else {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
        ) {
            ChartLegend()
            Spacer(modifier = Modifier.height(16.dp))

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(220.dp),
                verticalAlignment = Alignment.Bottom
            ) {
                // Y-Axis Labels
                Column(
                    modifier = Modifier
                        .fillMaxHeight()
                        .padding(end = 8.dp),
                    verticalArrangement = Arrangement.SpaceBetween,
                    horizontalAlignment = Alignment.End
                ) {
                    Text(maxValue.toString(), style = MaterialTheme.typography.labelSmall)
                    Text((maxValue / 2).toString(), style = MaterialTheme.typography.labelSmall)
                    Text("0", style = MaterialTheme.typography.labelSmall)
                }

                // Chart Bars
                Row(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxHeight(),
                    horizontalArrangement = Arrangement.SpaceAround,
                    verticalAlignment = Alignment.Bottom
                ) {
                    weeklyStats.forEach { stat ->
                        Column(
                            modifier = Modifier.weight(1f),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Bottom
                        ) {
                            Row(
                                verticalAlignment = Alignment.Bottom,
                                horizontalArrangement = Arrangement.spacedBy(2.dp),
                                modifier = Modifier
                                    .weight(1f)
                                    .fillMaxWidth(0.8f)
                            ) {
                                Bar(value = stat.newlyAdded, maxValue = maxValue, color = MaterialTheme.semanticColors.stageGradient1)
                                Bar(value = stat.completed, maxValue = maxValue, color = MaterialTheme.semanticColors.stageGradient3)
                                Bar(value = stat.answeredRight, maxValue = maxValue, color = MaterialTheme.semanticColors.stageGradient5)
                            }
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = stat.day,
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun RowScope.Bar(value: Int, maxValue: Int, color: Color) {
    var startAnimation by remember { mutableStateOf(false) }
    val barHeight by animateFloatAsState(
        targetValue = if (startAnimation) value.toFloat() / maxValue.toFloat() else 0f,
        animationSpec = tween(durationMillis = 1000),
        label = "barHeightAnimation"
    )

    LaunchedEffect(Unit) {
        delay(200) // Small delay to ensure the UI is ready before animating
        @Suppress("AssignedValueIsNeverRead")
        startAnimation = true
    }

    Box(
        modifier = Modifier
            .weight(1f)
            .fillMaxHeight(barHeight)
            .clip(RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp))
            .background(color)
    )
}

@Composable
private fun ChartLegend() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        LegendItem(color = MaterialTheme.semanticColors.stageGradient1, label = stringResource(R.string.label_added))
        LegendItem(color = MaterialTheme.semanticColors.stageGradient3, label = stringResource(R.string.label_completed))
        LegendItem(color = MaterialTheme.semanticColors.stageGradient5, label = stringResource(R.string.label_correct))
    }
}

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

@ThemePreviews
@Composable
fun WeeklyActivityChartWidgetPreview() {
    val sampleStats = listOf(
        WeeklyActivityStat("Mon", 10, 5, 20),
        WeeklyActivityStat("Tue", 12, 3, 15),
        WeeklyActivityStat("Wed", 8, 8, 25),
        WeeklyActivityStat("Thu", 15, 2, 18),
        WeeklyActivityStat("Fri", 5, 10, 30),
        WeeklyActivityStat("Sat", 7, 6, 22),
        WeeklyActivityStat("Sun", 9, 4, 17)
    )
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .padding(16.dp),
        contentAlignment = Alignment.Center
    ) {
        WeeklyActivityChartWidget(weeklyStats = sampleStats)
    }
}