@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.vocabulary

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.launch

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

    val itemsWithoutGrammar by vocabularyViewModel.allItemsWithoutGrammar.collectAsState()
    val isGenerating by vocabularyViewModel.isGenerating.collectAsState()

    var showFetchGrammarDialog by remember { mutableStateOf(false) }

    @Suppress("UnusedVariable") val onClose = { navController.popBackStack() }

    if (itemsWithoutGrammar.isEmpty() && !isGenerating) {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            AppTopAppBar(
                title = stringResource(R.string.title_items_without_grammar),
                onNavigateBack = { navController.popBackStack() },
            )
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.no_items_without_grammar),
                    textAlign = TextAlign.Center,
                    style = MaterialTheme.typography.bodyLarge,
                )
            }
        }
    } else {
        // Use the generic AllCardsListScreen to display the items
        AllCardsListScreen(
            itemsToShow = itemsWithoutGrammar,
            onNavigateToItem = { item ->
                @Suppress("HardCodedStringLiteral")
                navController.navigate("vocabulary_detail/${item.id}")
            },
            onNavigateBack = { navController.popBackStack() }
        )
    }

    Box(modifier = Modifier
        .fillMaxSize()
        .padding(bottom = 80.dp), contentAlignment = Alignment.BottomCenter) {
        if (itemsWithoutGrammar.isNotEmpty() && !isGenerating) {
            AppButton(onClick = { showFetchGrammarDialog = true }) {
                Text(text = stringResource(R.string.fetch_all_grammar_infos))
            }
        }
    }

    if (showFetchGrammarDialog) {
        val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
        val scope = rememberCoroutineScope()

        ModalBottomSheet(
            onDismissRequest = { showFetchGrammarDialog = false },
            sheetState = sheetState
        ) {
            if (itemsWithoutGrammar.size <= 2) {
                // Directly fetch all items without slider for 1 or 2 items
                val itemsToFetch = itemsWithoutGrammar
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                        .padding(bottom = 16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = stringResource(R.string.fetching_for_d_items, itemsToFetch.size),
                        style = MaterialTheme.typography.titleMedium
                    )
                    Spacer(Modifier.height(24.dp))
                    AppButton(
                        onClick = {
                            scope.launch {
                                showFetchGrammarDialog = false
                                vocabularyViewModel.fetchAndApplyGrammaticalDetailsForList(itemsToFetch)
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !isGenerating
                    ) {
                        if (isGenerating) {
                            CircularProgressIndicator(modifier = Modifier.size(24.dp))
                        } else {
                            Text(stringResource(R.string.start_fetching))
                        }
                    }
                }
            } else {
                // Use slider for more than 2 items
                var sliderValue by remember { mutableFloatStateOf(1f) }
                val itemsToFetch = itemsWithoutGrammar.take(sliderValue.toInt())

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                        .padding(bottom = 16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = stringResource(R.string.select_number_of_items_to_fetch),
                        style = MaterialTheme.typography.titleMedium
                    )
                    Spacer(Modifier.height(16.dp))
                    AppSlider(
                        value = sliderValue,
                        onValueChange = { sliderValue = it },
                        valueRange = 1f..minOf(50f, itemsWithoutGrammar.size.toFloat()),
                        steps = minOf(50, itemsWithoutGrammar.size) - 2,
                        modifier = Modifier.fillMaxWidth()
                    )
                    Text(
                        text = stringResource(R.string.fetching_for_d_items, sliderValue.toInt()),
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Spacer(Modifier.height(24.dp))
                    AppButton(
                        onClick = {
                            scope.launch {
                                showFetchGrammarDialog = false
                                vocabularyViewModel.fetchAndApplyGrammaticalDetailsForList(itemsToFetch)
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !isGenerating
                    ) {
                        if (isGenerating) {
                            CircularProgressIndicator(modifier = Modifier.size(24.dp))
                        } else {
                            Text(stringResource(R.string.start_fetching))
                        }
                    }
                }
            }
        }
    }

    // A small indicator to show that the process is ongoing
    if (isGenerating) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            Card(
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
            ) {
                Column(
                    modifier = Modifier.padding(24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    CircularProgressIndicator()
                    Text(stringResource(R.string.fetching_grammar_details))
                }
            }
        }
    }
}