@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.library

import android.os.Parcelable
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.rememberLazyListState
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.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.Folder
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
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.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.R.string.text_add_new_word_to_list
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.NavigationRoutes
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppSwitch
import eu.gaudian.translator.view.composable.BottomSheetMenuItem
import eu.gaudian.translator.view.composable.MultipleLanguageDropdown
import eu.gaudian.translator.view.dialogs.AddCategoryDialog
import eu.gaudian.translator.view.dialogs.CategorySelectionDialog
import eu.gaudian.translator.view.dialogs.StageSelectionDialog
import eu.gaudian.translator.viewmodel.LanguageConfigViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel.SortOrder
import kotlinx.coroutines.launch
import kotlinx.parcelize.Parcelize

@Parcelize
data class LibraryFilterState(
    val searchQuery: String = "",
    val selectedStage: VocabularyStage? = null,
    val sortOrder: SortOrder = SortOrder.NEWEST_FIRST,
    val categoryIds: List<Int> = emptyList(),
    val dueTodayOnly: Boolean = false,
    val selectedLanguageIds: List<Int> = emptyList(),
    val selectedWordClass: String? = null
) : Parcelable

@Composable
fun LibraryScreen(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val scope = rememberCoroutineScope()
    val activity = LocalContext.current.findActivity()
    val lazyListState = rememberLazyListState()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)

    var filterState by rememberSaveable { mutableStateOf(LibraryFilterState()) }
    var showFilterSheet by remember { mutableStateOf(false) }
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)

    var selection by remember { mutableStateOf<Set<Long>>(emptySet()) }
    val isInSelectionMode = selection.isNotEmpty()

    var showCategoryDialog by remember { mutableStateOf(false) }
    var showStageDialog by remember { mutableStateOf(false) }
    var showAddMenu by remember { mutableStateOf(false) }
    var showAddCategoryDialog by remember { mutableStateOf(false) }
    
    var isCategoriesView by remember { mutableStateOf(false) }

    val allLanguages by languageViewModel.allLanguages.collectAsStateWithLifecycle(initialValue = emptyList())
    val languagesPresent by vocabularyViewModel.languagesPresent.collectAsStateWithLifecycle(initialValue = emptySet())
    val categories by vocabularyViewModel.categories.collectAsStateWithLifecycle()

    val vocabularyItemsFlow = remember(filterState) {
        vocabularyViewModel.filterVocabularyItems(
            languages = filterState.selectedLanguageIds,
            query = filterState.searchQuery.takeIf { it.isNotBlank() },
            categoryIds = filterState.categoryIds,
            stage = filterState.selectedStage,
            wordClass = filterState.selectedWordClass,
            dueTodayOnly = filterState.dueTodayOnly,
            sortOrder = filterState.sortOrder
        )
    }

    val vocabularyItems by vocabularyItemsFlow.collectAsStateWithLifecycle(initialValue = emptyList())

    var isHeaderVisible by remember { mutableStateOf(true) }
    var previousIndex by remember { mutableIntStateOf(0) }
    var previousScrollOffset by remember { mutableIntStateOf(0) }

    // Set navigation context when vocabulary items are loaded
    LaunchedEffect(vocabularyItems) {
        if (vocabularyItems.isNotEmpty()) {
            vocabularyViewModel.setNavigationContext(vocabularyItems, vocabularyItems.first().id)
        }
    }

    LaunchedEffect(isCategoriesView, isInSelectionMode) {
        if (isCategoriesView || isInSelectionMode) {
            isHeaderVisible = true
        }
    }

    LaunchedEffect(lazyListState, isCategoriesView, isInSelectionMode) {
        if (isCategoriesView || isInSelectionMode) return@LaunchedEffect
        snapshotFlow { lazyListState.firstVisibleItemIndex to lazyListState.firstVisibleItemScrollOffset }
            .collect { (index, offset) ->
                val isScrollingDown = index > previousIndex || (index == previousIndex && offset > previousScrollOffset)
                val isAtTop = index == 0 && offset <= 4
                isHeaderVisible = if (isAtTop) true else !isScrollingDown
                previousIndex = index
                previousScrollOffset = offset
            }
    }

    Box(
        modifier = modifier.fillMaxSize(),
        contentAlignment = Alignment.TopCenter
    ) {
        Column(
            modifier = Modifier
                .widthIn(max = 700.dp)
                .fillMaxSize()
                .padding(horizontal = 16.dp),
        ) {
            AnimatedVisibility(
                visible = isHeaderVisible,
                enter = fadeIn() + expandVertically(),
                exit = fadeOut() + shrinkVertically()
            ) {
                Column {
                    Spacer(modifier = Modifier.height(24.dp))

                    if (isInSelectionMode) {
                        SelectionTopBar(
                            selectionCount = selection.size,
                            onCloseClick = { selection = emptySet() },
                            onSelectAllClick = {
                                selection = if (selection.size == vocabularyItems.size) emptySet()
                                           else vocabularyItems.map { it.id.toLong() }.toSet()
                            },
                            onDeleteClick = {
                                vocabularyViewModel.deleteVocabularyItemsById(selection.map { it.toInt() })
                                selection = emptySet()
                            },
                            onMoveToCategoryClick = { showCategoryDialog = true },
                            onMoveToStageClick = { showStageDialog = true },
                            isRemoveEnabled = false,
                            onRemoveFromCategoryClick = {}
                        )
                    } else {
                        LibraryTopBar(
                            onAddClick = { showAddMenu = true }
                        )
                    }

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

                    SearchBar(
                        searchQuery = filterState.searchQuery,
                        onQueryChanged = { filterState = filterState.copy(searchQuery = it) },
                        onFilterClick = { showFilterSheet = true }
                    )

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

                    SegmentedControl(
                        isCategoriesView = isCategoriesView,
                        onTabSelected = { isCategoriesView = it }
                    )

                    Spacer(modifier = Modifier.height(24.dp))
                }
            }

            LibraryViewContainer(
                isCategoriesView = isCategoriesView,
                categoriesContent = {
                    CategoriesView(
                        categories = categories,
                        onCategoryClick = { category ->
                            @Suppress("HardCodedStringLiteral")
                            navController.navigate("${NavigationRoutes.CATEGORY_DETAIL}/${category.id}")
                        },
                        onExploreMoreClick = {
                            navController.navigate(NavigationRoutes.CATEGORY_LIST)
                        }
                    )
                },
                allCardsContent = {
                    AllCardsView(
                        vocabularyItems = vocabularyItems,
                        allLanguages = allLanguages,
                        selection = selection,
                        listState = lazyListState,
                        onItemClick = { item ->
                            if (isInSelectionMode) {
                                selection = if (selection.contains(item.id.toLong())) {
                                    selection - item.id.toLong()
                                } else {
                                    selection + item.id.toLong()
                                }
                            } else {
                                vocabularyViewModel.setNavigationContext(vocabularyItems, item.id)
                                @Suppress("HardCodedStringLiteral")
                                navController.navigate("${NavigationRoutes.VOCABULARY_DETAIL}/${item.id}")
                            }
                        },
                        onItemLongClick = { item ->
                            if (!isInSelectionMode) {
                                selection = setOf(item.id.toLong())
                            }
                        },
                        onDeleteClick = { item ->
                            vocabularyViewModel.deleteData(
                                VocabularyViewModel.DeleteType.VOCABULARY_ITEM, 
                                item = item
                            )
                        }
                    )
                },
                modifier = Modifier.weight(1f)
            )
        }
        
        // Floating Action Button for scrolling to top
        val showFab by remember { 
            derivedStateOf { lazyListState.firstVisibleItemIndex > 5 && !isInSelectionMode } 
        }
        AnimatedVisibility(
            visible = showFab,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 16.dp)
        ) {
            FloatingActionButton(
                onClick = { scope.launch { lazyListState.animateScrollToItem(0) } },
                shape = CircleShape,
                modifier = Modifier.size(50.dp),
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            ) {
                Icon(AppIcons.ArrowCircleUp, contentDescription = stringResource(R.string.cd_scroll_to_top))
            }
        }
    }

    if (showFilterSheet) {
        ModalBottomSheet(
            onDismissRequest = { showFilterSheet = false },
            sheetState = sheetState,
            containerColor = MaterialTheme.colorScheme.surface,
            dragHandle = { BottomSheetDefaults.DragHandle() }
        ) {
            FilterBottomSheetContent(
                currentFilterState = filterState,
                languageViewModel = languageViewModel,
                languagesPresent = allLanguages.filter { it.nameResId in languagesPresent },
                onApplyFilters = { newState ->
                    filterState = newState
                    showFilterSheet = false
                    scope.launch { lazyListState.scrollToItem(0) }
                },
                onResetClick = {
                    filterState = LibraryFilterState()
                }
            )
        }
    }

    if (showCategoryDialog) {
        val selectedItems = vocabularyItems.filter { selection.contains(it.id.toLong()) }
        CategorySelectionDialog(
            onCategorySelected = {
                vocabularyViewModel.addVocabularyItemToCategories(
                    selectedItems,
                    it.mapNotNull { category -> category?.id }
                )
                showCategoryDialog = false
                selection = emptySet()
            },
            onDismissRequest = { showCategoryDialog = false }
        )
    }

    if (showAddMenu) {
        ModalBottomSheet(
            onDismissRequest = { showAddMenu = false },
            sheetState = sheetState,
            containerColor = MaterialTheme.colorScheme.surface,
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 32.dp) // Extra padding for system navigation bar
            ) {
                BottomSheetMenuItem(
                    icon = Icons.Rounded.Add, // Or any custom vector icon you prefer
                    title = stringResource(R.string.label_add_vocabulary),
                    subtitle = stringResource(text_add_new_word_to_list), // Suggest adding this to strings.xml
                    onClick = {
                        showAddMenu = false
                        navController.navigate(NavigationRoutes.NEW_WORD)
                    }
                )

                BottomSheetMenuItem(
                    icon = Icons.Rounded.Folder,
                    title = stringResource(R.string.label_add_category),
                    subtitle = stringResource(R.string.text_desc_organize_vocabulary_groups), // Suggest adding this to strings.xml
                    onClick = {
                        showAddMenu = false
                        showAddCategoryDialog = true
                    }
                )
            }
        }
    }

    if (showAddCategoryDialog) {
        AddCategoryDialog(onDismiss = { showAddCategoryDialog = false })
    }

    if (showStageDialog) {
        val selectedItems = vocabularyItems.filter { selection.contains(it.id.toLong()) }
        StageSelectionDialog(
            onStageSelected = { selectedStage ->
                selectedStage?.let {
                    vocabularyViewModel.addVocabularyItemToStage(selectedItems, it)
                }
                showStageDialog = false
                selection = emptySet()
            },
            onDismissRequest = { showStageDialog = false }
        )
    }
}

@Composable
fun FilterBottomSheetContent(
    currentFilterState: LibraryFilterState,
    languageViewModel: LanguageViewModel,
    languagesPresent: List<eu.gaudian.translator.model.Language>,
    onApplyFilters: (LibraryFilterState) -> Unit,
    onResetClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var selectedStage by rememberSaveable { mutableStateOf(currentFilterState.selectedStage) }
    var dueTodayOnly by rememberSaveable { mutableStateOf(currentFilterState.dueTodayOnly) }
    var selectedLanguageIds by rememberSaveable { mutableStateOf(currentFilterState.selectedLanguageIds) }
    var selectedWordClass by rememberSaveable { mutableStateOf(currentFilterState.selectedWordClass) }
    var sortOrder by rememberSaveable { mutableStateOf(currentFilterState.sortOrder) }

    val context = LocalContext.current
    val activity = LocalContext.current.findActivity()
    val languageConfigViewModel: LanguageConfigViewModel = hiltViewModel(activity)
    val allWordClasses by languageConfigViewModel.allWordClasses.collectAsStateWithLifecycle()

    Column(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(bottom = 32.dp)
            .navigationBarsPadding()
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = stringResource(R.string.label_filter_cards),
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )
            TextButton(onClick = {
                selectedStage = null
                dueTodayOnly = false
                selectedLanguageIds = emptyList()
                selectedWordClass = null
                sortOrder = SortOrder.NEWEST_FIRST
                onResetClick()
            }) {
                Text(stringResource(R.string.label_reset))
            }
        }

        HorizontalDivider(color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.1f))
        Spacer(modifier = Modifier.height(16.dp))

        Column(
            modifier = Modifier
                .weight(1f, fill = false)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            // Sort Order
            Column {
                Text(
                    text = stringResource(R.string.label_sort_by).uppercase(),
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    letterSpacing = 1.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    SortOrder.entries.forEach { order ->
                        FilterChip(
                            selected = sortOrder == order,
                            onClick = { sortOrder = order },
                            label = { 
                                Text(order.name.replace('_', ' ').lowercase()
                                    .replaceFirstChar { it.titlecase() }) 
                            }
                        )
                    }
                }
            }

            // Due Today
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = stringResource(R.string.text_due_today_only).uppercase(),
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    letterSpacing = 1.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                AppSwitch(checked = dueTodayOnly, onCheckedChange = { dueTodayOnly = it })
            }

            // Stages
            Column {
                Text(
                    text = "STAGES",
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    letterSpacing = 1.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    FilterChip(
                        selected = selectedStage == null,
                        onClick = { selectedStage = null },
                        label = { Text(stringResource(R.string.label_all_stages)) }
                    )
                    VocabularyStage.entries.forEach { stage ->
                        FilterChip(
                            selected = selectedStage == stage,
                            onClick = { selectedStage = stage },
                            label = { Text(stage.toString(context)) }
                        )
                    }
                }
            }

            // Languages
            Column {
                Text(
                    text = stringResource(R.string.language).uppercase(),
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    letterSpacing = 1.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 12.dp)
                )
                MultipleLanguageDropdown(
                    languageViewModel = languageViewModel,
                    onLanguagesSelected = { languages ->
                        selectedLanguageIds = languages.map { it.nameResId }
                    },
                    alternateLanguages = languagesPresent
                )
            }

            // Word Class
            if (allWordClasses.isNotEmpty()) {
                Column {
                    Text(
                        text = stringResource(R.string.filter_by_word_type).uppercase(),
                        style = MaterialTheme.typography.labelMedium,
                        fontWeight = FontWeight.Bold,
                        letterSpacing = 1.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(bottom = 12.dp)
                    )
                    FlowRow(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        FilterChip(
                            selected = selectedWordClass == null,
                            onClick = { selectedWordClass = null },
                            label = { Text(stringResource(R.string.label_all_types)) }
                        )
                        allWordClasses.forEach { wordClass ->
                            FilterChip(
                                selected = selectedWordClass == wordClass,
                                onClick = { selectedWordClass = wordClass },
                                label = { Text(wordClass.replaceFirstChar { it.titlecase() }) }
                            )
                        }
                    }
                }
            }
        }

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

        Button(
            onClick = {
                onApplyFilters(
                    currentFilterState.copy(
                        selectedStage = selectedStage,
                        dueTodayOnly = dueTodayOnly,
                        selectedLanguageIds = selectedLanguageIds,
                        selectedWordClass = selectedWordClass,
                        sortOrder = sortOrder
                    )
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp),
            shape = RoundedCornerShape(28.dp)
        ) {
            Text(
                text = stringResource(R.string.label_apply_filters),
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
        }
    }
}
