package eu.gaudian.translator.view.vocabulary

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
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.draw.clip
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.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
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.dialogs.CategoryDropdown
import eu.gaudian.translator.viewmodel.VocabularyViewModel

@Composable
fun NewWordReviewScreen(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(activity)

    val generatedItems 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),
                onNavigateBack = { navController.popBackStack() }
            )
        },
        modifier = modifier.fillMaxSize()
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .padding(paddingValues)
                .fillMaxSize()
        ) {
            SummaryHeader(
                totalCount = generatedItems.size,
                selectedCount = selectedItems.size,
                modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp)
            )

            if (generatedItems.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(24.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.text_no_data_available),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            } else {
                ReviewList(
                    generatedItems = generatedItems,
                    selectedItems = selectedItems,
                    duplicates = duplicates,
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 16.dp)
                )
            }

            Text(
                text = stringResource(R.string.select_list_optional),
                style = MaterialTheme.typography.labelLarge,
                modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)
            )
            CategoryDropdown(
                onCategorySelected = { selectedCategories = it },
                noneSelectable = false,
                multipleSelectable = true,
                onlyLists = true,
                addCategory = true,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp)
            )

            ActionRow(
                selectedCount = selectedItems.size,
                onCancel = { navController.popBackStack() },
                onConfirm = {
                    val selectedCategoryIds = selectedCategories.filterNotNull().map { it.id }
                    vocabularyViewModel.addVocabularyItems(selectedItems.toList(), selectedCategoryIds)
                    @Suppress("HardCodedStringLiteral")
                    navController.popBackStack("new_word", inclusive = false)
                },
                modifier = Modifier.padding(16.dp)
            )
        }
    }
}

@Composable
private fun SummaryHeader(
    totalCount: Int,
    selectedCount: Int,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = stringResource(R.string.found_items),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = stringResource(R.string.text_amount_2d, totalCount),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            Column(horizontalAlignment = Alignment.End) {
                Text(
                    text = stringResource(R.string.label_add_, selectedCount),
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.primary
                )
                Text(
                    text = stringResource(R.string.select_items_to_add),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
private fun ReviewList(
    generatedItems: List<VocabularyItem>,
    selectedItems: MutableList<VocabularyItem>,
    duplicates: List<Boolean>,
    modifier: Modifier = Modifier
) {
    val duplicateLabel = stringResource(R.string.duplicate)
    LazyColumn(modifier = modifier) {
        itemsIndexed(generatedItems) { index, item ->
            val isDuplicate = duplicates.getOrNull(index) == true
            val isSelected = selectedItems.contains(item)

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 6.dp),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = if (isDuplicate) {
                        MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.25f)
                    } else {
                        MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f)
                    }
                )
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppCheckbox(
                        checked = isSelected,
                        onCheckedChange = { checked ->
                            if (checked) {
                                selectedItems.add(item)
                            } else {
                                selectedItems.remove(item)
                            }
                        }
                    )
                    Spacer(modifier = Modifier.size(12.dp))
                    Column(modifier = Modifier.weight(1f)) {
                        Text(text = item.wordFirst, style = MaterialTheme.typography.titleMedium)
                        Text(text = item.wordSecond, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                    if (isDuplicate) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .clip(RoundedCornerShape(12.dp))
                                .background(MaterialTheme.colorScheme.error.copy(alpha = 0.15f))
                                .padding(horizontal = 8.dp, vertical = 4.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.WarningAmber,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.error
                            )
                            Spacer(modifier = Modifier.size(4.dp))
                            Text(
                                text = duplicateLabel,
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.error
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ActionRow(
    selectedCount: Int,
    onCancel: () -> Unit,
    onConfirm: () -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        TextButton(onClick = onCancel) {
            Text(stringResource(R.string.label_cancel))
        }
        AppButton(
            onClick = onConfirm,
            enabled = selectedCount > 0
        ) {
            Text(stringResource(R.string.label_add_, selectedCount))
        }
    }
}