package eu.gaudian.translator.view.dictionary

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.communication.FileInfo
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.viewmodel.DictionaryViewModel

@Composable
fun DictionaryManagerContent(
    dictionaryViewModel: DictionaryViewModel,
) {
    val manifest by dictionaryViewModel.manifest.collectAsState()
    val downloadedDictionaries by dictionaryViewModel.downloadedDictionaries.collectAsState()
    val orphanedFiles by dictionaryViewModel.orphanedFiles.collectAsState()
    val downloadProgress by dictionaryViewModel.downloadProgress.collectAsState()
    val isDownloading by dictionaryViewModel.isDownloading.collectAsState()

    var showDeleteAllDialog by remember { mutableStateOf(false) }

    if (manifest == null) return

    AppCard(
        title = stringResource(R.string.label_dictionary_manager),
        text = stringResource(R.string.text_dictionary_manager_description),
        expandable = true
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            if (manifest!!.files.isNotEmpty()) {
                DictionaryDownloadList(
                    files = manifest!!.files,
                    downloadedDictionaries = downloadedDictionaries,
                    downloadProgress = downloadProgress,
                    isDownloading = isDownloading,
                    dictionaryViewModel = dictionaryViewModel
                )
            }

            if (orphanedFiles.isNotEmpty()) {
                OrphanedFilesList(
                    files = orphanedFiles,
                    dictionaryViewModel = dictionaryViewModel
                )
            }

            if ((downloadedDictionaries.isNotEmpty() || orphanedFiles.isNotEmpty())) {
                AppButton(
                    onClick = { showDeleteAllDialog = true },
                    enabled = !isDownloading,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error,
                        contentColor = MaterialTheme.colorScheme.onError
                    ),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp)
                ) {
                    Text(stringResource(R.string.label_delete_all))
                }
            }

            if (manifest!!.files.isEmpty() && orphanedFiles.isEmpty()) {
                Text(
                    text = stringResource(R.string.text_no_dictionaries_available),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(top = 16.dp)
                )
            }
        }
    }

    if (showDeleteAllDialog) {
        DeleteAllDialog(
            onConfirm = {
                dictionaryViewModel.deleteAllDictionaries()
                @Suppress("AssignedValueIsNeverRead")
                showDeleteAllDialog = false
            },
            onDismiss = {
                @Suppress("AssignedValueIsNeverRead")
                showDeleteAllDialog = false
            }
        )
    }
}

@Composable
private fun DictionaryDownloadList(
    files: List<FileInfo>,
    downloadedDictionaries: List<FileInfo>,
    downloadProgress: Float?,
    isDownloading: Boolean,
    dictionaryViewModel: DictionaryViewModel
) {
    // Local state to track which ID is currently being processed
    var currentDownloadingId by remember { mutableStateOf<String?>(null) }

    // Reset when progress clears
    LaunchedEffect(downloadProgress) {
        if (downloadProgress == null) currentDownloadingId = null
    }

    Text(
        text = stringResource(R.string.text_available_dictionaries),
        style = MaterialTheme.typography.titleMedium,
        fontWeight = FontWeight.Bold,
        modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
    )

    Column {
        files.forEach { fileInfo ->
            val isDownloaded = downloadedDictionaries.any { it.id == fileInfo.id }
            // Using ViewModel's getDictionaryUiItems for pre-calculated values
            val uiItems = dictionaryViewModel.getDictionaryUiItems(files, downloadedDictionaries)
            val uiItem = uiItems.find { it.fileInfo.id == fileInfo.id }

            DictionaryManagerItem(
                fileInfo = fileInfo,
                isDownloaded = uiItem?.isDownloaded ?: isDownloaded,
                hasUpdate = uiItem?.hasUpdate ?: false,
                size = uiItem?.size ?: fileInfo.assets.sumOf { it.sizeBytes },
                downloadProgress = if (fileInfo.id == currentDownloadingId) downloadProgress else null,
                isDownloading = isDownloading,
                onDownload = {
                    currentDownloadingId = fileInfo.id
                    dictionaryViewModel.downloadDictionary(fileInfo)
                },
                onUpdate = {
                    currentDownloadingId = fileInfo.id
                    dictionaryViewModel.downloadDictionary(fileInfo)
                },
                onDelete = { dictionaryViewModel.deleteDictionary(fileInfo) }
            )
        }
    }
}

@Composable
private fun OrphanedFilesList(
    files: List<FileInfo>,
    dictionaryViewModel: DictionaryViewModel
) {
    Text(
        text = stringResource(R.string.label_orphaned_files),
        style = MaterialTheme.typography.titleMedium,
        fontWeight = FontWeight.Bold,
        modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
    )
    Text(
        text = stringResource(R.string.text_these_files_exist_locally),
        style = MaterialTheme.typography.bodySmall,
        modifier = Modifier.padding(bottom = 8.dp)
    )

    Column {
        files.forEach { fileInfo ->
            OrphanedFileItem(
                fileInfo = fileInfo,
                size = dictionaryViewModel.getDictionarySize(fileInfo),
                onDelete = { dictionaryViewModel.deleteOrphanedFile(fileInfo) }
            )
        }
    }
}
