package eu.gaudian.translator.view.dialogs

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.TagCategory
import eu.gaudian.translator.model.VocabularyCategory
import eu.gaudian.translator.model.VocabularyFilter
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.MultipleLanguageDropdown
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import kotlinx.coroutines.flow.collectLatest

@Suppress("HardCodedStringLiteral")
@Composable
fun EditCategoryDialog(
    languageViewModel: LanguageViewModel,
    categoryViewModel: CategoryViewModel,
    onDismiss: () -> Unit,
) {
    var categoryToEdit by remember { mutableStateOf<VocabularyCategory?>(null) }

    var categoryName by remember { mutableStateOf("") }
    var selectedLanguages by remember { mutableStateOf<List<Language>>(emptyList()) }
    var selectedStages by remember { mutableStateOf<List<VocabularyStage?>>(emptyList()) }

    LaunchedEffect(categoryViewModel.categoryToEdit) {
        if (categoryViewModel.categoryToEdit != 0) {
            categoryViewModel.getCategoryById(categoryViewModel.categoryToEdit).collectLatest { category ->
                categoryToEdit = category
                category?.let {
                    categoryName = it.name
                    // Only set languages and stages if it's a filter
                    if (it is VocabularyFilter) {
                        selectedLanguages = it.languages?.mapNotNull { id -> languageViewModel.getLanguageById(id).takeIf { l -> l.code != "error" } } ?: emptyList()
                        selectedStages = it.stages ?: emptyList()
                    }
                }
            }
        }
    }

    AppDialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(
                modifier = Modifier.padding(24.dp)
            ) {
                Text(
                    text = stringResource(R.string.text_edit_category),
                    style = MaterialTheme.typography.titleLarge,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // Content
                if (categoryToEdit != null) {
                    Column(modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp)
                    ) {
                        AppOutlinedTextField(
                            value = categoryName,
                            onValueChange = { categoryName = it },
                            label = { Text(stringResource(R.string.text_category_name)) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 8.dp)
                        )

                        if (categoryToEdit is VocabularyFilter) {
                            MultipleLanguageDropdown(
                                languageViewModel = languageViewModel,
                                modifier = Modifier.fillMaxWidth(),
                                onLanguagesSelected = { languages ->
                                    selectedLanguages = languages
                                },
                            )
                            VocabularyStageDropDown(
                                preselectedStages = selectedStages.filterNotNull(),
                                onStageSelected = { newStages ->
                                    @Suppress("UNCHECKED_CAST")
                                    val list = newStages
                                    selectedStages = list.filterNotNull()
                                },
                                modifier = Modifier.fillMaxWidth(),
                                multipleSelectable = true
                            )
                        }
                    }
                }

                // Buttons
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    TextButton(onClick = onDismiss) {
                        Text(stringResource(R.string.label_cancel))
                    }
                    TextButton(
                        enabled = categoryToEdit != null && categoryName.isNotBlank(),
                        onClick = {
                            categoryToEdit?.let { category ->
                                val updatedCategory = when (category) {
                                    is TagCategory -> category.copy(name = categoryName.trim())
                                    is VocabularyFilter -> category.copy(
                                        name = categoryName.trim(),
                                        languages = selectedLanguages.map { it.nameResId }.ifEmpty { null },
                                        stages = selectedStages.filterNotNull().ifEmpty { null }
                                    )
                                }
                                updatedCategory.let {
                                    categoryViewModel.updateCategory(it)
                                }
                            }
                            onDismiss()
                        }
                    ) { Text(stringResource(R.string.label_save)) }
                }
            }
        }
    }
}