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.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
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.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
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.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.VocabularyCategory
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCheckbox
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.hints.HintDefinition
import eu.gaudian.translator.viewmodel.VocabularyViewModel

@Composable
fun VocabularyReviewScreen(
    onConfirm: (List<VocabularyItem>, List<Int>) -> Unit,
    onCancel: () -> Unit
) {
    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(activity)

    val generatedItems: List<VocabularyItem> by vocabularyViewModel.generatedVocabularyItems.collectAsState()

    val selectedItems = remember { mutableStateListOf<VocabularyItem>() }
    val duplicates = remember { mutableStateListOf<Boolean>() }
    var selectedCategories by remember { mutableStateOf<List<VocabularyCategory?>>(emptyList()) }

    LaunchedEffect(generatedItems) {
        val duplicateResults = vocabularyViewModel.findDuplicates(generatedItems)
        duplicates.clear()
        duplicates.addAll(duplicateResults)
        selectedItems.clear()
        selectedItems.addAll(generatedItems.filterIndexed { index, _ -> !duplicateResults[index] })
    }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.found_items),
                hintContent = HintDefinition.REVIEW.hint()
            )
        },
    ) { paddingValues ->
        Column(modifier = Modifier.padding(paddingValues)) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(text = stringResource(R.string.select_items_to_add), style = MaterialTheme.typography.titleMedium)
                val allSelected = generatedItems.isNotEmpty() && selectedItems.size == generatedItems.size
                AppCheckbox(
                    checked = allSelected,
                    onCheckedChange = { isChecked ->
                        if (isChecked) {
                            selectedItems.clear()
                            selectedItems.addAll(generatedItems)
                        } else {
                            selectedItems.clear()
                        }
                    }
                )
            }
            val duplicate = stringResource(R.string.duplicate)
            LazyColumn(
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 16.dp)
            ) {
                itemsIndexed(generatedItems) { index, item ->
                    val isDuplicate = duplicates.getOrNull(index) == true
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        AppCheckbox(
                            checked = selectedItems.contains(item),
                            onCheckedChange = { isChecked ->
                                if (isChecked) {
                                    selectedItems.add(item)
                                } else {
                                    selectedItems.remove(item)
                                }
                            }
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Column {
                            Text(text = item.wordFirst, style = MaterialTheme.typography.bodyLarge)
                            Text(text = item.wordSecond, style = MaterialTheme.typography.bodyMedium)
                        }
                        if (isDuplicate) {
                            Spacer(modifier = Modifier.weight(1f))
                            Text(duplicate, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
                        }
                    }
                }
            }
            Text(
                text = stringResource(R.string.select_list_optional),
                style = MaterialTheme.typography.labelLarge,
                modifier = Modifier.padding(8.dp)
            )
            CategoryDropdown(
                onCategorySelected = { selectedCategories = it },
                noneSelectable = false,
                multipleSelectable = true,
                onlyLists = true,
                addCategory = true,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
            )
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.End
            ) {
                TextButton(onClick = onCancel) {
                    Text(stringResource(R.string.label_cancel))
                }
                Spacer(modifier = Modifier.width(8.dp))
                AppButton(
                    onClick = {
                        val selectedCategoryIds = selectedCategories.filterNotNull().map { it.id }
                        onConfirm(selectedItems.toList(), selectedCategoryIds)
                    },
                    enabled = selectedItems.isNotEmpty()
                ) {
                    Text(stringResource(R.string.label_add_, selectedItems.size))
                }
            }
        }
    }
}
