package eu.gaudian.translator.view.vocabulary

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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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 androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppAlertDialog
import eu.gaudian.translator.view.composable.AppDialog
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.CategorySelectionDialog
import eu.gaudian.translator.view.dialogs.StageSelectionDialog
import eu.gaudian.translator.view.vocabulary.card.VocabularyDisplayCard
import eu.gaudian.translator.view.vocabulary.card.VocabularyExerciseCard
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.launch
import kotlin.time.ExperimentalTime

@Composable
fun VocabularyCardHost(
    navController: NavController,
    itemId: Int,
    exerciseMode: Boolean = false,
    spellingMode: Boolean = false,
    switchOrder: Boolean? = false,
    onAnswerSelected: ((Boolean) -> Unit)? = null,
    onBackPressed: (() -> Unit)? = null
) {
    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val scope = rememberCoroutineScope()

    val navigationItems by vocabularyViewModel.currentNavigationItems.collectAsState()
    val navigationPosition by vocabularyViewModel.currentNavigationPosition.collectAsState()

    var vocabularyItem by remember { mutableStateOf<VocabularyItem?>(null) }

    LaunchedEffect(itemId) {
        vocabularyItem = vocabularyViewModel.getVocabularyItemById(itemId)
    }

    var isEditing by remember { mutableStateOf(false) }
    var onSaveEdit by remember { mutableStateOf<(() -> Unit)?>(null) }
    var onCancelEdit by remember { mutableStateOf<(() -> Unit)?>(null) }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                modifier = Modifier.height(56.dp),
                title = stringResource(R.string.item_details),
                onNavigateBack = { navController.popBackStack() },
                actions = {
                    if (!isEditing) {
                        // Previous button
                        if (navigationPosition > 0) {
                            IconButton(onClick = {
                                if (vocabularyViewModel.navigateToPreviousItem()) {
                                    val prevItem = navigationItems[navigationPosition - 1]
                                    scope.launch {

                                        @Suppress("AssignedValueIsNeverRead")
                                        vocabularyItem = vocabularyViewModel.getVocabularyItemById(prevItem.id)
                                    }
                                }
                            }) {
                                Icon(
                                    AppIcons.ArrowLeft,
                                    contentDescription = stringResource(R.string.previous_item),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            }
                        }

                        // Next button
                        if (navigationPosition < navigationItems.size - 1) {
                            IconButton(onClick = {
                                if (vocabularyViewModel.navigateToNextItem()) {
                                    val nextItem = navigationItems[navigationPosition + 1]
                                    scope.launch {
                                        @Suppress("AssignedValueIsNeverRead")
                                        vocabularyItem = vocabularyViewModel.getVocabularyItemById(nextItem.id)
                                    }
                                }
                            }) {
                                Icon(
                                    AppIcons.ArrowRight,
                                    contentDescription = stringResource(R.string.next_item),
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            }
                        }
                    }
                }
            )
        }
    ) { paddingValues ->
        Box(modifier = Modifier.padding(paddingValues)) {
            if (vocabularyItem == null) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
            } else {
                val currentVocabularyItem = vocabularyItem!!

                var isFlipped by remember { mutableStateOf(false) }
                var showQuitDialog by remember { mutableStateOf(false) }
                var showStatisticsDialog by remember { mutableStateOf(false) }
                var showCategoryDialog by remember { mutableStateOf(false) }
                var showStageDialog by remember { mutableStateOf(false) }
                var showDeleteDialog by remember { mutableStateOf(false) }
                LaunchedEffect(currentVocabularyItem.id) {
                    isEditing = false
                    onSaveEdit = null
                    onCancelEdit = null
                }

                val lifecycleOwner = LocalLifecycleOwner.current
                val stats by vocabularyViewModel
                    .getVocabularyItemDetailsFlow(currentVocabularyItem.id)
                    .collectAsStateWithLifecycle(
                        initialValue = null,
                        lifecycle = lifecycleOwner.lifecycle
                    )

                @Suppress("ControlFlowWithEmptyBody")
                if (exerciseMode && onBackPressed != null) {
                    //TODO consider BackPressHandler(onBackPressed = { showQuitDialog = true })
                }

                if(showDeleteDialog){
                    AppAlertDialog(
                        title = {
                            Text(stringResource(R.string.text_delete_vocabulary_item))
                        },
                        text = {
                            Text(stringResource(R.string.text_are_you_sure_delete_vocabulary_item))
                        },
                        confirmButton = {
                            TextButton(
                                onClick = {
                                    vocabularyViewModel.deleteData(
                                        VocabularyViewModel.DeleteType.VOCABULARY_ITEM_BY_ID,
                                        currentVocabularyItem.id
                                    )
                                    if (exerciseMode) {
                                        onAnswerSelected?.invoke(false)
                                    } else {
                                        navController.popBackStack()
                                    }
                                }
                            ) {
                                Text(text = stringResource(R.string.label_delete))
                            }
                        },
                        dismissButton = @Composable {
                            TextButton(
                                onClick = { showDeleteDialog = false },
                            ) {
                                Text(text = stringResource(R.string.label_cancel))
                            }
                        },
                        onDismissRequest = { showDeleteDialog = false },
                    )
                }

                // Main content
                Column(
                    modifier = Modifier.fillMaxSize(),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    if (!exerciseMode && isEditing) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Center,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            OutlinedButton(
                                onClick = { onCancelEdit?.invoke() },
                                shape = RoundedCornerShape(16.dp)
                            ) {
                                Text(text = stringResource(R.string.label_cancel))
                            }
                            Spacer(modifier = Modifier.width(8.dp))
                            Button(
                                onClick = { onSaveEdit?.invoke() },
                                shape = RoundedCornerShape(16.dp),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.primary
                                )
                            ) {
                                Text(text = stringResource(R.string.label_save))
                            }
                        }
                    }

                    if (exerciseMode) {
                        VocabularyExerciseCard(
                            vocabularyItem = currentVocabularyItem,
                            switchOrder = switchOrder == true,
                            isFlipped = isFlipped,
                            navController = navController,
                        )
                    } else {
                        VocabularyDisplayCard(
                            vocabularyItem = currentVocabularyItem,
                            switchOrder = switchOrder == true,
                            isFlipped = isFlipped,
                            onStatisticsClick = { showStatisticsDialog = true },
                            onMoveToCategoryClick = { showCategoryDialog = true },
                            onMoveToStageClick = { showStageDialog = true },
                            onDeleteClick = { showDeleteDialog = true },
                            navController = navController,
                            onEditStateChange = { editing ->
                                isEditing = editing
                                if (!editing) {
                                    onSaveEdit = null
                                    onCancelEdit = null
                                }
                            },
                            onEditActionHandlersReady = { onSave, onCancel ->
                                onSaveEdit = onSave
                                onCancelEdit = onCancel
                            },
                        )
                    }
                }

                // Dialogs are unaffected by the layout change
                if (showQuitDialog) {
                    QuitDialog(
                        onConfirm = {
                            onBackPressed?.invoke()
                            showQuitDialog = false
                        },
                        onDismiss = { showQuitDialog = false }
                    )
                }

                if (showStatisticsDialog) {
                    StatisticsDialog(
                        vocabularyItem = currentVocabularyItem,
                        stats = stats,
                        onDismiss = { showStatisticsDialog = false }
                    )
                }

                if (showCategoryDialog) {
                    CategorySelectionDialog(
                        onCategorySelected = {
                                vocabularyViewModel.addVocabularyItemToCategories(
                                    listOf(currentVocabularyItem),
                                    it.mapNotNull { category -> category?.id }
                                )
                            //showCategoryDialog = false
                        },
                        onDismissRequest = { showCategoryDialog = false }
                    )
                }

                if (showStageDialog) {
                    StageSelectionDialog(
                        onStageSelected = { stage ->
                            stage?.let {
                                vocabularyViewModel.addVocabularyItemToStage(
                                    listOf(currentVocabularyItem),
                                    it
                                )
                            }
                            showStageDialog = false
                        },
                        onDismissRequest = { showStageDialog = false }
                    )
                }

                LaunchedEffect(spellingMode) {
                    @Suppress("ControlFlowWithEmptyBody")
                    if (spellingMode) {
                       //TODO implement // Setup spelling mode logic if needed
                    }
                }
            }
        }
    }
}


@Composable
private fun QuitDialog(
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AppAlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.quit)) },
        text = { Text(text = stringResource(R.string.text_are_you_sure_you_want_to_quit)) },
        confirmButton = { TextButton(onClick = onConfirm) { Text(stringResource(R.string.label_yes)) } },
        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.no)) } }
    )
}

@OptIn(ExperimentalTime::class)
@Composable
private fun StatisticsDialog(
    vocabularyItem: VocabularyItem,
    stats: VocabularyViewModel.VocabularyItemDetails?,
    onDismiss: () -> Unit
) {
    AppDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.label_statistics)) },
        content = {
            if (stats != null) {
                Column {
                    Text(stringResource(R.string.stage__, stats.stage.toString(context = LocalContext.current)))
                    Text(stringResource(R.string.last_correct, stats.lastCorrectAnswer ?: "-"))
                    Text(stringResource(R.string.last_incorrect, stats.lastIncorrectAnswer ?: "-"))
                    Text(stringResource(R.string.correct_answers_, stats.correctAnswerCount))
                    Text(stringResource(R.string.incorrect_answers, stats.incorrectAnswerCount))
                    Text(stringResource(R.string.item_id, vocabularyItem.id))
                    vocabularyItem.languageFirstId?.let { Text(stringResource(R.string.languagefirst_id, it)) }
                    vocabularyItem.languageSecondId?.let { Text(stringResource(R.string.languagesecond_id, it)) }
                }
            } else {
                Text(stringResource(R.string.statistics_are_loading))
            }
        },
    )
}

@ThemePreviews
@Composable
fun VocabularyCardHostPreview() {
    val navController = NavController(LocalContext.current)
    VocabularyCardHost(navController = navController, itemId = 1)
}

@ThemePreviews
@Composable
fun QuitDialogPreview() {
    QuitDialog(onConfirm = {}, onDismiss = {})
}

@ThemePreviews
@Composable
fun VocabularyCardHostWithNavigationPreview() {
    val navController = NavController(LocalContext.current)
    VocabularyCardHost(
        navController = navController,
        itemId = 1,
        onBackPressed = {}
    )
}

@Suppress("HardCodedStringLiteral")
@OptIn(ExperimentalTime::class)
@ThemePreviews
@Composable
fun StatisticsDialogPreview() {
    val vocabularyItem = VocabularyItem(id = 1, languageFirstId = 101, languageSecondId = 102, wordFirst = "Hello", wordSecond = "Hola")
    val stats = VocabularyViewModel.VocabularyItemDetails(
        stage = VocabularyStage.NEW,
        lastCorrectAnswer = null,
        lastIncorrectAnswer = null,
        correctAnswerCount = 5,
        incorrectAnswerCount = 2
    )
    StatisticsDialog(vocabularyItem = vocabularyItem, stats = stats, onDismiss = {})
}