package eu.gaudian.translator.view.settings

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.animateContentSize
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.FlowRow
import androidx.compose.foundation.layout.Row
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.hints.HintDefinition
import eu.gaudian.translator.viewmodel.SettingsViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.roundToInt

@Composable
fun VocabularyProgressOptionsScreen(
    navController: NavController,
) {
    val activity = LocalContext.current.findActivity()
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)



    val exportFileLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult(),
        onResult = { result -> vocabularyViewModel.handleSaveResult(result) }
    )

    LaunchedEffect(exportFileLauncher) {
        vocabularyViewModel.initializeSaveFileLauncher(exportFileLauncher)
    }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.label_vocabulary_settings),
                onNavigateBack = { navController.popBackStack() },
                hintContent = HintDefinition.VOCABULARY_PROGRESS.hint()
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Daily Goal Settings
            AppCard {
                val dailyGoal by settingsViewModel.dailyGoal.collectAsStateWithLifecycle()
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {

                    @Suppress("USELESS_ELVIS", "HardCodedStringLiteral")
                    SettingsSlider(
                        label = stringResource(R.string.label_target_correct_answers_per_day),
                        value = dailyGoal ?: 10,
                        onValueChange = { settingsViewModel.setDailyGoal(it) },
                        valueRange = 10f..100f,
                        steps = 17 // Allows snapping in steps of 5
                    )
                    Text(
                        text = stringResource(R.string.text_daily_goal_description),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            // Criteria Settings
            AppCard {
                val criteriaCorrect by settingsViewModel.criteriaCorrect.collectAsStateWithLifecycle()
                val criteriaWrong by settingsViewModel.criteriaWrong.collectAsStateWithLifecycle()
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = stringResource(R.string.label_learning_criteria),
                        style = MaterialTheme.typography.titleMedium
                    )
                    // Slider for "Min correct to advance"
                    SettingsSlider(
                        label = stringResource(R.string.min_correct_to_advance),
                        value = criteriaCorrect,
                        onValueChange = { settingsViewModel.setCriteriaCorrect(it) },
                        valueRange = 1f..5f,
                        steps = 3 // Allows snapping to 1, 2, 3, 4, 5
                    )
                    // Slider for "Max wrong to demote"
                    SettingsSlider(
                        label = stringResource(R.string.max_wrong_to_demote),
                        value = criteriaWrong,
                        onValueChange = { settingsViewModel.setCriteriaWrong(it) },
                        valueRange = 1f..5f,
                        steps = 3
                    )
                }
            }

            // Interval Settings
            AppCard(
                expandable = true,
                initiallyExpanded = true,
                title = stringResource(R.string.label_interval_settings_in_days),
                text = stringResource(R.string.text_customize_the_intervals),
                ) {
                val intervals by settingsViewModel.intervals.collectAsStateWithLifecycle()
                Column(
                    modifier = Modifier
                        .padding(16.dp)
                        .animateContentSize(),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    IntervalTimeline(intervals = intervals)
                    intervals.forEach { (stageKey, days) ->
                        val displayLabel = labelForStage(stageKey)
                        IntervalSlider(
                            label = displayLabel,
                            value = days,
                            onValueChange = { newValue ->
                                settingsViewModel.setInterval(stageKey, newValue)
                            }
                        )
                    }

                    Spacer(Modifier.height(8.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextButton(onClick = { settingsViewModel.resetIntervalsToDefaults() }) {
                            Text(stringResource(R.string.reset_to_defaults))
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun SettingsSlider(
    label: String,
    value: Int,
    onValueChange: (Int) -> Unit,
    valueRange: ClosedFloatingPointRange<Float>,
    steps: Int
) {
    Column {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyLarge,
                modifier = Modifier.weight(1f)
            )
            Box(
                modifier = Modifier
                    .background(
                        MaterialTheme.colorScheme.primaryContainer,
                        RoundedCornerShape(8.dp)
                    )
                    .padding(horizontal = 12.dp, vertical = 4.dp)
            ) {
                Text(
                    text = value.toString(),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontWeight = FontWeight.Bold
                )
            }
        }
        Spacer(Modifier.height(4.dp))
        AppSlider(
            value = value.toFloat(),
            onValueChange = { onValueChange(it.roundToInt()) },
            valueRange = valueRange,
            steps = steps
        )
    }
}

@Composable
private fun IntervalTimeline(intervals: Map<String, Int>) {
    val totalDays = intervals.values.sum()
    val stageColors = listOf(
        MaterialTheme.colorScheme.primary,
        MaterialTheme.colorScheme.secondary,
        MaterialTheme.colorScheme.tertiary,
        Color(0xFF3F51B5), // Indigo
        Color(0xFF009688), // Teal
        Color(0xFFE91E63),  // Pink
        Color(0xFFFF9800)   // Orange for the 'Learned' stage
    )

    // Main layout for the timeline and its labels
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        // Build the string showing the sum of all stage days
        val calculationString = intervals.values
            .filter { it > 0 } // Exclude stages with 0 days from the text
            .joinToString(" + ")

        val fullText = if (calculationString.isNotEmpty()) {
            // Using a simple "days" string, adjust if you have a specific resource
            buildString {
        append(calculationString)
        append(" = ")
        append(totalDays)
        append(stringResource(R.string.text_days))
    }
        } else {
            buildString {
        append(totalDays)
                append(stringResource(R.string.text_days))
    }
        }

        // Display the full calculation string centered above the bar
        Text(
            text = fullText,
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Bold
        )

        // The timeline bar
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(20.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.surfaceContainerHighest)
        ) {
            intervals.onEachIndexed { index, (_, days) ->
                val weight = if (totalDays > 0) days.toFloat() / totalDays.toFloat() else 0f
                if (weight > 0) {
                    Box(
                        modifier = Modifier
                            .fillMaxHeight()
                            .weight(weight)
                            .background(stageColors.getOrElse(index) { Color.Gray })
                    )
                }
            }
        }

        // Spacer before the legend
        Spacer(modifier = Modifier.height(4.dp))

        // The legend using a FlowRow to ensure all items are visible
        FlowRow(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            intervals.keys.forEachIndexed { index, stageKey ->
                LegendItem(
                    color = stageColors.getOrElse(index) { Color.Gray },
                    icon = getIconForStage(stageKey),
                    stageName = labelForStage(stageKey)
                )
            }
        }
    }
}

@Composable
private fun getIconForStage(stageKey: String): ImageVector {
    return when (stageKey) {
        SettingsViewModel.STAGE_NEW -> AppIcons.StageNew
        SettingsViewModel.STAGE_1 -> AppIcons.Stage1
        SettingsViewModel.STAGE_2 -> AppIcons.Stage2
        SettingsViewModel.STAGE_3 -> AppIcons.Stage3
        SettingsViewModel.STAGE_4 -> AppIcons.Stage4
        SettingsViewModel.STAGE_5 -> AppIcons.Stage5
        SettingsViewModel.STAGE_LEARNED -> AppIcons.StageLearned
        else -> AppIcons.Error
    }
}

@Composable
private fun labelForStage(stageKey: String): String {
    return when (stageKey) {
        SettingsViewModel.STAGE_NEW -> stringResource(R.string.stage_new)
        SettingsViewModel.STAGE_1 -> stringResource(R.string.stage_1)
        SettingsViewModel.STAGE_2 -> stringResource(R.string.stage_2)
        SettingsViewModel.STAGE_3 -> stringResource(R.string.stage_3)
        SettingsViewModel.STAGE_4 -> stringResource(R.string.stage_4)
        SettingsViewModel.STAGE_5 -> stringResource(R.string.stage_5)
        SettingsViewModel.STAGE_LEARNED -> stringResource(R.string.stage_learned)
        else -> stageKey
    }
}

@Composable
private fun IntervalSlider(
    label: String,
    value: Int,
    onValueChange: (Int) -> Unit
) {
    // Constants for the logarithmic scale
    val minVal = 1f
    val maxVal = 180f

    fun valueToPos(v: Int): Float {
        val vv = v.toFloat().coerceAtLeast(minVal)
        return (ln(vv) - ln(minVal)) / (ln(maxVal) - ln(minVal))
    }
    fun posToValue(p: Float): Int {
        val logValue = ln(minVal) + (ln(maxVal) - ln(minVal)) * p
        return exp(logValue).roundToInt().coerceIn(minVal.toInt(), maxVal.toInt())
    }

    // Local slider position state to avoid jitter when ViewModel updates on every tick
    val initialPos = valueToPos(value)
    val localPosState = androidx.compose.runtime.remember(value) { androidx.compose.runtime.mutableFloatStateOf(initialPos) }

    val displayValue = posToValue(localPosState.floatValue)

    Column {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.SemiBold
            )
            Box(
                modifier = Modifier
                    .background(
                        MaterialTheme.colorScheme.primaryContainer,
                        RoundedCornerShape(8.dp)
                    )
                    .padding(horizontal = 12.dp, vertical = 4.dp)
            ) {
                Text(
                    text = stringResource(R.string.days_2d, displayValue),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontWeight = FontWeight.Bold
                )
            }
        }
        Spacer(Modifier.height(4.dp))
        AppSlider(
            value = localPosState.floatValue,
            onValueChange = { newSliderPosition ->
                localPosState.floatValue = newSliderPosition
            },
            valueRange = 0f..1f,
            onValueChangeFinished = {
                // Commit only when the user releases the thumb
                onValueChange(posToValue(localPosState.floatValue))
            }
        )
    }
}

@Composable
private fun LegendItem(color: Color, icon: ImageVector, stageName: String) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Box(
            modifier = Modifier
                .size(10.dp)
                .background(color, CircleShape)
        )
        Icon(
            imageVector = icon,
            contentDescription = stageName,
            modifier = Modifier.size(24.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@ThemePreviews
@Composable
fun VocabularyOptionsScreenPreview() {
    VocabularyProgressOptionsScreen(navController = NavController(LocalContext.current))
}