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

import android.annotation.SuppressLint
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.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.viewmodel.VocabularyViewModel

@SuppressLint("SuspiciousIndentation")
@Composable
fun DueTodayWidget(vocabularyViewModel: VocabularyViewModel, onStageClicked: (VocabularyStage) -> Unit) {
    val dueTodayItems = vocabularyViewModel.dueTodayItems.collectAsState().value
    val stageMapping = vocabularyViewModel.stageMapping.collectAsState().value
    val dueTodayCount = dueTodayItems.size
    val dueTodayByStage = dueTodayItems.groupingBy { stageMapping[it.id] ?: VocabularyStage.NEW }.eachCount()


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

            if (dueTodayCount > 0) {
                VocabularyStage.entries.forEach { stage ->
                    val stageCount = dueTodayByStage[stage] ?: 0
                    if (stageCount > 0) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { onStageClicked(stage) }
                                .padding(vertical = 4.dp)
                        ) {
                            DetailedStageProgressBar(
                                stage = stage,
                                itemCount = stageCount,
                                totalItems = stageMapping.values.count { it == stage },
                                onStageTapped = onStageClicked
                            )
                        }
                    }
                }
            } else {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 32.dp)
                ) {
                    Text(
                        text = stringResource(R.string.text_no_vocabulary_due_today),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
}