@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.vocabulary

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Badge
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.TagCategory
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.dialogs.AddCategoryDialog
import eu.gaudian.translator.view.dialogs.DeleteMultipleCategoriesDialog
import eu.gaudian.translator.view.vocabulary.widgets.CategoryCircleType
import eu.gaudian.translator.view.vocabulary.widgets.CategoryProgressCircle
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.ProgressViewModel

enum class SortOption {
    NAME,
    SIZE,
    COMPLETION_PERCENTAGE,
    NEW_ITEMS,
    IN_PROGRESS
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CategoryListScreen(
    onNavigateBack: () -> Unit,
    onCategoryClicked: (Int) -> Unit,
) {

    val activity = LocalContext.current.findActivity()
    val categoryViewModel : CategoryViewModel = hiltViewModel(activity)
    val progressViewModel : ProgressViewModel = hiltViewModel(activity)



    var sortOption by remember { mutableStateOf(SortOption.NAME) }
    var sortMenuExpanded by remember { mutableStateOf(false) }
    val categoryProgressList by progressViewModel.categoryProgressList.collectAsState(initial = emptyList())
    var showAddCategoryDialog by remember { mutableStateOf(false) }
    var showDeleteCategoryDialog by remember { mutableStateOf(false) }
    var selectedCategories by remember { mutableStateOf(emptySet<Int>()) }
    var isSelectionMode by remember { mutableStateOf(false) }
    val haptic = LocalHapticFeedback.current

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

    val sortedCategories = remember(categoryProgressList, sortOption) {
        when (sortOption) {
            SortOption.NAME -> categoryProgressList.sortedBy { it.vocabularyCategory.name }
            SortOption.SIZE -> categoryProgressList.sortedByDescending { it.totalItems }
            SortOption.COMPLETION_PERCENTAGE -> categoryProgressList.sortedByDescending { 
                if (it.totalItems > 0) it.itemsCompleted.toFloat() / it.totalItems else 0f 
            }
            SortOption.NEW_ITEMS -> categoryProgressList.sortedByDescending { it.newItems }
            SortOption.IN_PROGRESS -> categoryProgressList.sortedByDescending { it.itemsInStages }
        }
    }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = "TODO",
                navigationIcon = {
                    if (isSelectionMode) {
                        IconButton(onClick = {
                            isSelectionMode = false
                            selectedCategories = emptySet()
                        }) {
                            Icon(AppIcons.CheckCircle, contentDescription = stringResource(R.string.label_close))
                        }
                    } else {
                        IconButton(onClick = onNavigateBack) {
                            Icon(AppIcons.ArrowBack, contentDescription = stringResource(R.string.cd_back))
                        }
                    }
                },
                actions = {
                    if (isSelectionMode) {
                        if (selectedCategories.isNotEmpty()) {
                            IconButton(
                                onClick = { 
                                    showDeleteCategoryDialog = true 
                                },
                                enabled = true
                            ) {
                                Icon(AppIcons.Delete, contentDescription = stringResource(R.string.label_delete))
                            }
                        }
                        IconButton(
                            onClick = {
                                selectedCategories = if (selectedCategories.size == sortedCategories.size) {
                                    emptySet()
                                } else {
                                    sortedCategories.map { it.vocabularyCategory.id }.toSet()
                                }
                            }
                        ) {
                            if (selectedCategories.size == sortedCategories.size) {
                                Icon(AppIcons.Deselect, contentDescription = stringResource(R.string.deselect_all))
                                } else {
                                Icon(AppIcons.SelectAll, contentDescription = stringResource(R.string.select_all))
                                }
                        }
                    } else {
                        IconButton(onClick = { sortMenuExpanded = true }) {
                            Icon(AppIcons.Sort, contentDescription = stringResource(R.string.sort))
                        }
                    }
                    DropdownMenu(
                        expanded = sortMenuExpanded,
                        onDismissRequest = { sortMenuExpanded = false }
                    ) {
                        DropdownMenuItem(
                            text = { 
                                Text(
                                    text = stringResource(R.string.sort_by_name),
                                    color = if (sortOption == SortOption.NAME) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                                )
                            },
                            onClick = {
                                sortOption = SortOption.NAME
                                sortMenuExpanded = false
                            }
                        )
                        DropdownMenuItem(
                            text = { 
                                Text(
                                    text = stringResource(R.string.sort_by_size),
                                    color = if (sortOption == SortOption.SIZE) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                                )
                            },
                            onClick = {
                                sortOption = SortOption.SIZE
                                sortMenuExpanded = false
                            }
                        )
                        DropdownMenuItem(
                            text = { 
                                Text(
                                    text = stringResource(R.string.sort_by_completion_percentage),
                                    color = if (sortOption == SortOption.COMPLETION_PERCENTAGE) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                                )
                            },
                            onClick = {
                                sortOption = SortOption.COMPLETION_PERCENTAGE
                                sortMenuExpanded = false
                            }
                        )
                        DropdownMenuItem(
                            text = { 
                                Text(
                                    text = stringResource(R.string.sort_by_new_items),
                                    color = if (sortOption == SortOption.NEW_ITEMS) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                                )
                            },
                            onClick = {
                                sortOption = SortOption.NEW_ITEMS
                                sortMenuExpanded = false
                            }
                        )
                        DropdownMenuItem(
                            text = { 
                                Text(
                                    text = stringResource(R.string.sort_by_in_progress),
                                    color = if (sortOption == SortOption.IN_PROGRESS) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                                )
                            },
                            onClick = {
                                sortOption = SortOption.IN_PROGRESS
                                sortMenuExpanded = false
                            }
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            if (!isSelectionMode) {
                FloatingActionButton(
                    onClick = { showAddCategoryDialog = true },
                    shape = RoundedCornerShape(16.dp),
                    containerColor = MaterialTheme.colorScheme.primary,
                    contentColor = MaterialTheme.colorScheme.onPrimary,
                    elevation = FloatingActionButtonDefaults.elevation(defaultElevation = 8.dp)
                ) {
                    Icon(AppIcons.Add, contentDescription = stringResource(R.string.label_add_category))
                }
            }
        }
    ) { paddingValues ->
        LazyVerticalGrid(
            columns = GridCells.Adaptive(minSize = 128.dp),
            contentPadding = paddingValues,
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            modifier = Modifier.padding(16.dp)
        ) {
            items(sortedCategories.size) { index ->
                val data = sortedCategories[index]
                val categoryId = data.vocabularyCategory.id
                val isSelected = selectedCategories.contains(categoryId)
                
                Box(
                    modifier = Modifier
                        .combinedClickable(
                            onClick = {
                                if (isSelectionMode) {
                                    selectedCategories = if (isSelected) {
                                        selectedCategories - categoryId
                                    } else {
                                        selectedCategories + categoryId
                                    }
                                    if (selectedCategories.isEmpty()) {
                                        isSelectionMode = false
                                    }
                                } else {
                                    onCategoryClicked(categoryId)
                                }
                            },
                            onLongClick = {
                                haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                                isSelectionMode = true
                                selectedCategories = selectedCategories + categoryId
                            }
                        )
                ) {
                    Box(
                        modifier = if (isSelected) Modifier.background(
                            color = MaterialTheme.colorScheme.primary.copy(alpha = 0.1f),
                            shape = MaterialTheme.shapes.medium
                        ) else Modifier
                    ) {
                        CategoryProgressCircle(
                            category = data.vocabularyCategory.name,
                            totalItems = data.totalItems,
                            itemsCompleted = data.itemsCompleted,
                            itemsInStages = data.itemsInStages,
                            newItems = data.newItems,
                            onClick = null,
                            showPercentage = true,
                            type = if(data.vocabularyCategory is  TagCategory) CategoryCircleType.List else CategoryCircleType.Filter
                        )
                    }
                    
                    if (isSelectionMode) {
                        Checkbox(
                            checked = isSelected,
                            onCheckedChange = { checked ->
                                selectedCategories = if (checked) {
                                    selectedCategories + categoryId
                                } else {
                                    selectedCategories - categoryId
                                }
                                if (selectedCategories.isEmpty()) {
                                    isSelectionMode = false
                                }
                            },
                            modifier = Modifier
                                .align(Alignment.TopStart)
                                .padding(8.dp)
                                .size(24.dp)
                        )
                    }
                    
                    if (isSelected && !isSelectionMode) {
                        Badge(
                            modifier = Modifier
                                .align(Alignment.TopEnd)
                                .padding(8.dp)
                        ) {
                            Icon(
                                imageVector = AppIcons.CheckCircle,
                                contentDescription = stringResource(R.string.text_selected),
                                modifier = Modifier.size(16.dp)
                            )
                        }
                    }
                }
            }
        }
    }
    
    if (showDeleteCategoryDialog && selectedCategories.isNotEmpty()) {
        DeleteMultipleCategoriesDialog(
            categoryIds = selectedCategories.toList(),
            categoryViewModel = categoryViewModel,
            onDismiss = { showDeleteCategoryDialog = false },
            onConfirm = { 
                selectedCategories = emptySet()
                isSelectionMode = false
                showDeleteCategoryDialog = false
            }
        )
    }
}
