package com.github.nullptroma.wallenc.ui.screens.main.screens.vault

import android.widget.Toast
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.WindowInsets
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.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.github.nullptroma.wallenc.ui.R
import com.github.nullptroma.wallenc.ui.elements.StorageTree
import com.github.nullptroma.wallenc.ui.resources.UserNotification
import java.util.UUID

@Composable
fun VaultBrowserScreen(
    modifier: Modifier = Modifier,
    viewModel: AbstractVaultBrowserViewModel,
    onOpenStorageHome: (String) -> Unit,
) {
    val uiState by viewModel.state.collectAsStateWithLifecycle()
    val context = LocalContext.current
    var pendingNotification by remember { mutableStateOf<UserNotification?>(null) }

    LaunchedEffect(viewModel) {
        viewModel.userNotifications.collect { notification ->
            pendingNotification = notification
        }
    }
    val notificationText = when (val notification = pendingNotification) {
        is UserNotification.TextRes -> {
            if (notification.formatArgs.isEmpty()) {
                stringResource(notification.id)
            } else {
                stringResource(notification.id, *notification.formatArgs.toTypedArray())
            }
        }
        is UserNotification.Plain -> notification.message
        null -> null
    }
    LaunchedEffect(notificationText) {
        val text = notificationText ?: return@LaunchedEffect
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
        pendingNotification = null
    }

    val fabEnabled = uiState.addStorageFabEnabled
    val fabBusy = uiState.vaultListMutationActive
    val showFullscreenLoader = uiState.storagesList.isEmpty() && uiState.storagesRefreshing
    val showEmptyState = uiState.storagesList.isEmpty() && !uiState.storagesRefreshing
    val showRescan = viewModel.supportsStorageRescan
    val rescanEnabled = showRescan &&
        !uiState.vaultListMutationActive &&
        !uiState.storagesRefreshing
    val isUuidBusy: (UUID) -> Boolean = { uuid -> uuid in uiState.busyStorageUuids }

    val addFab: @Composable () -> Unit = {
        FloatingActionButton(
            onClick = {
                if (fabEnabled && !fabBusy) {
                    viewModel.createStorage()
                }
            },
            modifier = Modifier.alpha(if (fabEnabled && !fabBusy) 1f else 0.38f),
        ) {
            Icon(
                Icons.Filled.Add,
                contentDescription = stringResource(
                    when {
                        !fabEnabled -> R.string.vault_fab_add_storage_disabled_cd
                        fabBusy -> R.string.vault_fab_add_storage_busy_cd
                        else -> R.string.vault_fab_add_storage_cd
                    },
                ),
            )
        }
    }

    val vaultContent: @Composable (androidx.compose.foundation.layout.PaddingValues) -> Unit = { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
                .fillMaxSize(),
        ) {
            uiState.header?.let { header ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 12.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = stringResource(header.titleResId),
                            style = MaterialTheme.typography.headlineSmall,
                            color = MaterialTheme.colorScheme.onSurface,
                        )
                        header.subtitle?.let { subtitle ->
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = subtitle,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                            )
                        }
                    }
                    if (showRescan) {
                        FilledTonalButton(
                            onClick = { viewModel.rescanStorages() },
                            enabled = rescanEnabled,
                        ) {
                            Text(stringResource(R.string.vault_rescan_storages_action))
                        }
                    }
                }
            }
            if (!fabEnabled) {
                Text(
                    text = stringResource(R.string.vault_unavailable_banner),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 12.dp, vertical = 6.dp),
                )
            }
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth(),
            ) {
                when {
                    showEmptyState -> {
                        Text(
                            text = stringResource(
                                if (showRescan) {
                                    R.string.vault_empty_list_hint_remote
                                } else {
                                    R.string.vault_empty_list_hint
                                },
                            ),
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center,
                            modifier = Modifier
                                .align(Alignment.Center)
                                .padding(horizontal = 24.dp),
                        )
                    }
                    else -> {
                        LazyColumn(
                            modifier = Modifier.fillMaxSize(),
                        ) {
                            items(uiState.storagesList) { listItem ->
                                StorageTree(
                                    modifier = Modifier.padding(8.dp, 8.dp, 8.dp, 0.dp),
                                    tree = listItem,
                                    isUuidBusy = isUuidBusy,
                                    onClick = { onOpenStorageHome(it.value.uuid.toString()) },
                                    onRename = { tree, newName -> viewModel.rename(tree.value, newName) },
                                    onRemove = { tree -> viewModel.remove(tree.value) },
                                    onEncrypt = { tree, password, encryptPath, rememberPassword ->
                                        viewModel.enableEncryption(
                                            tree.value,
                                            password,
                                            encryptPath,
                                            rememberPassword,
                                        )
                                    },
                                    onOpenEncrypted = { tree, password, remember ->
                                        viewModel.openEncryptedStorage(tree.value, password, remember)
                                    },
                                    onCloseEncrypted = { tree -> viewModel.closeEncryptedStorage(tree.value) },
                                    onDisableEncryption = { tree -> viewModel.disableEncryption(tree.value) },
                                    getStatusTextRes = { tree -> viewModel.getStorageStatusRes(tree.value) },
                                    isEncryptionOpened = { tree -> viewModel.isEncryptionSessionOpen(tree.value) },
                                    isStorageSyncLockHeld = { info -> viewModel.isStorageSyncLockHeld(info) },
                                    onClearStorageSyncLock = { info -> viewModel.clearStorageSyncLock(info) },
                                )
                            }
                            item {
                                Spacer(modifier = Modifier.height(8.dp))
                            }
                        }
                    }
                }
            }
        }
    }

    Box(modifier = modifier) {
        Scaffold(
            contentWindowInsets = WindowInsets(0.dp),
            floatingActionButton = addFab,
            content = vaultContent,
        )

        if (showFullscreenLoader) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.scrim),
                )
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(64.dp),
                        color = MaterialTheme.colorScheme.primary,
                        trackColor = MaterialTheme.colorScheme.surfaceVariant,
                    )
                    Text(
                        text = stringResource(R.string.vault_loading_storages),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurface,
                        textAlign = TextAlign.Center,
                        modifier = Modifier.padding(horizontal = 24.dp),
                    )
                }
            }
        }
    }
}
