@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.view.vocabulary

import android.annotation.SuppressLint
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.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.TagCategory
import eu.gaudian.translator.model.VocabularyFilter
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.utils.findActivity
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.view.composable.PrimaryButton
import eu.gaudian.translator.view.dialogs.DeleteCategoryDialog
import eu.gaudian.translator.view.dialogs.DeleteItemsDialog
import eu.gaudian.translator.view.dialogs.EditCategoryDialog
import eu.gaudian.translator.view.vocabulary.widgets.CategoryProgressCircle
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.ProgressViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel

@SuppressLint("ContextCastToActivity")
@Composable
fun CategoryDetailScreen(
    categoryId: Int,
    onBackClick: () -> Unit,
    onNavigateToItem: (VocabularyItem) -> Unit,
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val activity = LocalContext.current.findActivity()
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val progressViewModel: ProgressViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)

    val category by categoryViewModel.getCategoryById(categoryId).collectAsState(initial = null)
    val categoryProgressList by progressViewModel.categoryProgressList.collectAsState()
    val categoryProgress = categoryProgressList.find { it.vocabularyCategory.id == categoryId }

    val context = LocalContext.current
    val title = when (val cat = category) {
        is TagCategory -> cat.name
        is VocabularyFilter -> cat.name
        else -> stringResource(R.string.text_loading_3d)
    }

    val languages = languageViewModel.allLanguages.collectAsState(initial = emptyList())

    val subtitle = when (val cat = category) {
        is TagCategory -> stringResource(R.string.text_manual_vocabulary_list)
        is VocabularyFilter -> buildString {
            val hasLangList = !cat.languages.isNullOrEmpty()
            val hasPair = cat.languagePairs != null
            val hasStages = !cat.stages.isNullOrEmpty()
            if (!hasLangList && !hasPair && !hasStages) {
                append(stringResource(R.string.text_filter_all_items))
            } else {
                //append(stringResource(R.string.filter))
                append(" ")
                if (hasPair) {
                    val (a,b) = cat.languagePairs
                    append("[${languages.value.find{ it.nameResId == a }?.name} - ${languages.value.find{ it.nameResId == b }?.name}]")
                } else if (hasLangList) {
                    append(cat.languages.joinToString(", ") { langId -> languages.value.find { it.nameResId == langId }?.name.toString() })
                } else {
                    append(stringResource(R.string.text_all_languages))
                }
                append(" | ")
                if (hasStages) append(cat.stages.joinToString(", ") { it.toString(context) }) else append(stringResource(R.string.label_all_stages))
            }
        }
        else -> ""
    }

    var showMenu by remember { mutableStateOf(false) }
    val showDeleteCategoryDialog by categoryViewModel.showDeleteCategoryDialog.collectAsState(initial = false)
    val showDeleteItemsDialog by categoryViewModel.showDeleteItemsDialog.collectAsState(initial = false)
    val showEditCategoryDialog by categoryViewModel.showEditCategoryDialog.collectAsState(initial = false)

    AppScaffold(
        modifier = modifier,
        topBar = {
            Column(
                modifier = Modifier.background(MaterialTheme.colorScheme.surface)
            ) {
                AppTopAppBar(
                    title = {
                        Column {
                            Text(
                                text = title,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                            Text(
                                text = subtitle,
                                style = MaterialTheme.typography.bodySmall,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    },
                    navigationIcon = {
                        IconButton(onClick = onBackClick) {
                            Icon(
                                AppIcons.ArrowBack,
                                contentDescription = stringResource(R.string.cd_back)
                            )
                        }
                    },
                    actions = {
                        IconButton(onClick = { showMenu = !showMenu }) {
                            Icon(
                                imageVector = AppIcons.MoreVert,
                                contentDescription = stringResource(R.string.text_more_options)
                            )
                        }
                        DropdownMenu(

                            expanded = showMenu,
                            onDismissRequest = { showMenu = false },
                            modifier = Modifier.width(220.dp)
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.text_edit_category)) },
                                onClick = {
                                    categoryViewModel.setShowEditCategoryDialog(true, categoryId)
                                    showMenu = false
                                }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.text_export_category)) },
                                onClick = {
                                    vocabularyViewModel.saveCategory(categoryId)
                                    showMenu = false
                                }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.delete_items_category)) },
                                onClick = {
                                    categoryViewModel.setShowDeleteItemsDialog(true, categoryId)
                                    showMenu = false
                                }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.text_delete_category)) },
                                onClick = {
                                    categoryViewModel.setShowDeleteCategoryDialog(true, categoryId)
                                    showMenu = false
                                }
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        // TODO: Review this
                        containerColor = MaterialTheme.colorScheme.surface
                    )
                )

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp, horizontal = 16.dp),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if (categoryProgress != null) {
                        Box(modifier = Modifier.weight(1f)) {
                            CategoryProgressCircle(
                                totalItems = categoryProgress.totalItems,
                                itemsCompleted = categoryProgress.itemsCompleted,
                                itemsInStages = categoryProgress.itemsInStages,
                                newItems = categoryProgress.newItems,
                                circleSize = 80.dp,
                            )
                        }
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }

                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .padding(start = 8.dp)
                    ) {
                        PrimaryButton(
                            text = stringResource(R.string.label_start),
                            icon = AppIcons.Play,
                            onClick = {
                                val categories = listOf(category)
                                val categoryIds = categories.joinToString(",") { it?.id.toString() }
                                navController.navigate("vocabulary_exercise/false?categories=$categoryIds")
                            },
                            modifier = Modifier.heightIn(max = 80.dp)
                        )
                    }
                }
            }
        }
    ) { paddingValues ->
        Column(modifier = Modifier.padding(paddingValues)) {
            VocabularyListScreen(
                categoryId = categoryId,
                showDueTodayOnly = false,
                onNavigateToItem = onNavigateToItem,
                navController = navController, // Pass the received navController here
                isRemoveFromCategoryEnabled = category is TagCategory,
                showTopBar = false,
                enableNavigationButtons = true
            )

            // Dialogs
            if (showDeleteCategoryDialog) {
                DeleteCategoryDialog(
                    onDismiss = { categoryViewModel.setShowDeleteCategoryDialog(false, categoryId) },
                    viewModel = categoryViewModel,
                )
            }
            if (showDeleteItemsDialog) {
                DeleteItemsDialog(
                    onDismiss = { categoryViewModel.setShowDeleteItemsDialog(false, categoryId) },
                    categoryId = categoryId
                )
            }
            if (showEditCategoryDialog) {
                EditCategoryDialog(
                    onDismiss = { categoryViewModel.setShowEditCategoryDialog(false, categoryId) },
                    languageViewModel = languageViewModel,
                    categoryViewModel = categoryViewModel,
                )
            }
        }
    }
}