@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.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
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.TextAlign
import androidx.compose.ui.tooling.preview.Preview
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.composable.SecondaryButton
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.CategoryProgress
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(" ")
                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 = title,
                    onNavigateBack = { navController.popBackStack() },
                    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_export_category)) },
                                onClick = {
                                    vocabularyViewModel.saveCategory(categoryId)
                                    showMenu = false
                                },
                                leadingIcon = { Icon(AppIcons.Share, contentDescription = null) }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.delete_items_category)) },
                                onClick = {
                                    categoryViewModel.setShowDeleteItemsDialog(true, categoryId)
                                    showMenu = false
                                },
                                leadingIcon = { Icon(AppIcons.Delete, contentDescription = null) }
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.surface
                    )
                )

                // Category Header Card with Progress and Action Buttons
                CategoryHeaderCard(
                    subtitle = subtitle,
                    categoryProgress = categoryProgress,
                    onStartExerciseClick = {
                        val categories = listOf(category)
                        val categoryIds = categories.joinToString(",") { it?.id.toString() }
                        navController.navigate("vocabulary_exercise/false?categories=$categoryIds")
                    },
                    onEditClick = {
                        categoryViewModel.setShowEditCategoryDialog(true, categoryId)
                    },
                    onDeleteClick = {
                        categoryViewModel.setShowDeleteCategoryDialog(true, categoryId)
                    }
                )
            }
        }
    ) { paddingValues ->
        Column(modifier = Modifier.padding(paddingValues)) {
            AllCardsListScreen(
                categoryId = categoryId,
                showDueTodayOnly = false,
                onNavigateToItem = onNavigateToItem,
                navController = navController,
                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,
                )
            }
        }
    }
}

@Composable
fun CategoryHeaderCard(
    subtitle: String,
    categoryProgress: CategoryProgress?,
    onStartExerciseClick: () -> Unit,
    onEditClick: () -> Unit,
    onDeleteClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // Subtitle
            if (subtitle.isNotBlank()) {
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = 16.dp)
                )
            }

            // Progress Circle
            if (categoryProgress != null) {
                CategoryProgressCircle(
                    totalItems = categoryProgress.totalItems,
                    itemsCompleted = categoryProgress.itemsCompleted,
                    itemsInStages = categoryProgress.itemsInStages,
                    newItems = categoryProgress.newItems,
                    circleSize = 120.dp,
                )
                Spacer(modifier = Modifier.height(24.dp))
            }

            // Action Buttons
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // Start Exercise Button (Primary)
                PrimaryButton(
                    text = stringResource(R.string.label_start_exercise),
                    icon = AppIcons.Play,
                    onClick = onStartExerciseClick,
                    modifier = Modifier.weight(1f)
                )
            }

            Spacer(modifier = Modifier.height(12.dp))

            // Secondary Action Buttons
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // Edit Button
                SecondaryButton(
                    text = stringResource(R.string.label_edit),
                    icon = AppIcons.Edit,
                    onClick = onEditClick,
                    modifier = Modifier.weight(1f)
                )

                // Delete Button
                SecondaryButton(
                    text = stringResource(R.string.label_delete),
                    icon = AppIcons.Delete,
                    onClick = onDeleteClick,
                    modifier = Modifier.weight(1f)
                )
            }
        }
    }
}

// ==================== PREVIEWS ====================

@Preview(showBackground = true)
@Composable
fun CategoryHeaderCardPreview() {
    MaterialTheme {
        CategoryHeaderCard(
            subtitle = "German - English | All Stages",
            categoryProgress = null,
            onStartExerciseClick = {},
            onEditClick = {},
            onDeleteClick = {}
        )
    }
}

@Preview(showBackground = true)
@Composable
fun CategoryHeaderCardWithProgressPreview() {
    MaterialTheme {
        CategoryHeaderCard(
            subtitle = "Travel Vocabulary",
            categoryProgress = CategoryProgress(
                vocabularyCategory = TagCategory(
                    1,
                    "Travel"
                ),
                totalItems = 50,
                newItems = 15,
                itemsInStages = 25,
                itemsCompleted = 10
            ),
            onStartExerciseClick = {},
            onEditClick = {},
            onDeleteClick = {}
        )
    }
}
