package eu.gaudian.translator.view.vocabulary

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
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.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.LanguageLevels
import eu.gaudian.translator.model.MyAppLanguageLevel
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.viewmodel.ProgressViewModel

@Composable
fun LanguageProgressScreen(navController: NavController) {

    val activity = LocalContext.current.findActivity()
    val progressViewModel : ProgressViewModel = hiltViewModel(activity)

    val wordsLearned = progressViewModel.totalWordsCompleted.collectAsState().value


    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.your_language_journey),
                onNavigateBack = { navController.popBackStack() }
            )
        },
        content = { innerPadding ->
            LevelsRoadmap(
                wordsLearned = wordsLearned,
                modifier = Modifier.padding(innerPadding)
            )
        }
    )
}

@Composable
private fun LevelsRoadmap(wordsLearned: Int, modifier: Modifier = Modifier) {
    val allLevels = LanguageLevels.all
    val currentLevel = LanguageLevels.getLevelForWords(wordsLearned)
    val nextLevel = LanguageLevels.getNextLevel(wordsLearned)
    var selectedLevelForDialog by remember { mutableStateOf<MyAppLanguageLevel?>(null) }

    Box(modifier = modifier.fillMaxSize()) {
        LazyColumn(
            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 24.dp)
        ) {
            item {
                JourneyHeader(currentLevel, nextLevel, wordsLearned)
                Spacer(modifier = Modifier.height(32.dp))
            }

            items(allLevels.size) { index ->
                val level = allLevels[index]
                RoadmapNode(
                    level = level,
                    isUnlocked = wordsLearned >= level.wordsKnown,
                    isCurrent = level == currentLevel,
                    isFirst = index == 0,
                    isLast = index == allLevels.lastIndex,
                    onClick = {
                        if (wordsLearned >= level.wordsKnown) {
                            selectedLevelForDialog = level
                        }
                    }
                )
            }
        }

        // Show the dialog when a level is selected
        selectedLevelForDialog?.let { level ->
            LevelDetailDialog(
                level = level,
                onDismiss = { selectedLevelForDialog = null }
            )
        }
    }
}

@Composable
private fun JourneyHeader(
    currentLevel: MyAppLanguageLevel,
    nextLevel: MyAppLanguageLevel?,
    wordsLearned: Int
) {
    val progress = if (nextLevel != null && nextLevel.wordsKnown > currentLevel.wordsKnown) {
        (wordsLearned - currentLevel.wordsKnown).toFloat() / (nextLevel.wordsKnown - currentLevel.wordsKnown).toFloat()
    } else {
        1f
    }
    val animatedProgress by animateFloatAsState(
        targetValue = progress.coerceIn(0f, 1f),
        animationSpec = tween(1000, easing = FastOutSlowInEasing),
        label = "ProgressAnimation"
    )

    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(4.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = stringResource(R.string.current_level),
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.primary
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = stringResource(id = currentLevel.nameResId),
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold
            )
            Spacer(modifier = Modifier.height(16.dp))

            if (nextLevel != null) {
                Text(
                    text = stringResource(R.string.next_, stringResource(id = nextLevel.nameResId)),
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.SemiBold
                )
                Spacer(modifier = Modifier.height(8.dp))
                LinearProgressIndicator(
                    progress = { animatedProgress },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(8.dp)
                        .clip(CircleShape),
                    strokeCap = StrokeCap.Round
                )
                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                    Text(
                        text = stringResource(R.string.words_2d, currentLevel.wordsKnown),
                        style = MaterialTheme.typography.labelSmall
                    )
                    Text(
                        text = stringResource(R.string.words, nextLevel.wordsKnown),
                        style = MaterialTheme.typography.labelSmall
                    )
                }
            } else {
                Text(
                    text = stringResource(R.string.text_mastered_final_level),
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
    }
}

@Composable
private fun RoadmapNode(
    level: MyAppLanguageLevel,
    isUnlocked: Boolean,
    isCurrent: Boolean,
    isFirst: Boolean,
    isLast: Boolean,
    onClick: () -> Unit
) {
    val pathColor = if (isUnlocked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant
    @Suppress("HardCodedStringLiteral") val infiniteTransition = rememberInfiniteTransition(label = "pulse_transition")
    @Suppress("HardCodedStringLiteral") val pulseScale by if (isCurrent) {
        infiniteTransition.animateFloat(
            initialValue = 1f,
            targetValue = 1.15f,
            animationSpec = infiniteRepeatable(
                animation = tween(800, easing = FastOutSlowInEasing),
                repeatMode = RepeatMode.Reverse
            ),
            label = "pulse_scale"
        )
    } else {
        animateFloatAsState(targetValue = 1f, label = "static_scale")
    }

    Row(modifier = Modifier.height(IntrinsicSize.Min)) {
        // Path and Icon Column
        Column(
            modifier = Modifier.width(48.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Canvas(modifier = Modifier
                .weight(0.4f)
                .fillMaxWidth()) {
                if (!isFirst) {
                    drawLine(
                        color = pathColor,
                        start = Offset(center.x, 0f),
                        end = Offset(center.x, size.height),
                        strokeWidth = 3.dp.toPx(),
                        cap = StrokeCap.Round
                    )
                }
            }
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .scale(pulseScale)
                    .background(
                        if (isCurrent) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
                        CircleShape
                    )
                    .border(width = 3.dp, color = pathColor, shape = CircleShape),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(id = level.iconResId),
                    contentDescription = stringResource(id = level.nameResId),
                    modifier = Modifier.size(28.dp),
                    tint = if (isUnlocked) Color.Unspecified else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
                )
            }

            // Line below the icon
            Canvas(modifier = Modifier
                .weight(0.6f)
                .fillMaxWidth()) {
                if (!isLast) {
                    drawLine(
                        color = pathColor,
                        start = Offset(center.x, 0f),
                        end = Offset(center.x, size.height),
                        strokeWidth = 3.dp.toPx(),
                        cap = StrokeCap.Round
                    )
                }
            }
        }

        // Card with level details
        Card(
            modifier = Modifier
                .padding(start = 16.dp, bottom = 24.dp)
                .align(Alignment.CenterVertically)
                .clickable(enabled = isUnlocked, onClick = onClick),
            elevation = CardDefaults.cardElevation(if (isUnlocked) 4.dp else 1.dp),
            colors = CardDefaults.cardColors(
                containerColor = if (isUnlocked) MaterialTheme.colorScheme.surfaceContainer else MaterialTheme.colorScheme.surface.copy(alpha = 0.5f)
            )
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = stringResource(id = level.nameResId),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = stringResource(R.string.words_2d, level.wordsKnown),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                    if (isUnlocked) {
                        Icon(
                            imageVector = AppIcons.CheckCircle,
                            contentDescription = stringResource(R.string.cd_achieved),
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                }
                if (isUnlocked) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = stringResource(id = level.descriptionResId),
                        style = MaterialTheme.typography.bodySmall,
                        lineHeight = 16.sp
                    )
                }
            }
        }
    }
}

@Composable
private fun LevelDetailDialog(level: MyAppLanguageLevel, onDismiss: () -> Unit) {
    AppDialog(onDismissRequest = onDismiss) {
        Surface(
            shape = MaterialTheme.shapes.large,
            color = MaterialTheme.colorScheme.surface,
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Icon(
                    painter = painterResource(id = level.iconResId),
                    contentDescription = null,
                    modifier = Modifier.size(120.dp),
                    tint = Color.Unspecified
                )
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = stringResource(id = level.nameResId),
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = stringResource(R.string.words_required, level.wordsKnown),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.primary
                )
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = stringResource(id = level.descriptionResId),
                    style = MaterialTheme.typography.bodyMedium,
                    textAlign = TextAlign.Center
                )
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun LanguageProgressScreenPreview() {
    LanguageProgressScreen(navController = NavController(LocalContext.current))
}