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

import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalResources
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.github.nullptroma.wallenc.ui.R
import com.github.nullptroma.wallenc.ui.resources.toUserNotification
import com.github.nullptroma.wallenc.vault.contract.CloudBrand
import com.github.nullptroma.wallenc.vault.contract.VaultLinkOutcome

@Composable
fun RemoteVaultsScreen(
    modifier: Modifier = Modifier,
    viewModel: RemoteVaultsViewModel = hiltViewModel(),
    onOpenVault: (RemoteVaultListItem) -> Unit,
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val context = LocalContext.current
    val resources = LocalResources.current

    Box {
        Scaffold(
            modifier = modifier,
            contentWindowInsets = WindowInsets(0.dp),
            floatingActionButton = {
                FloatingActionButton(
                    onClick = {
                        if (!uiState.isBusy) viewModel.setAddChoiceVisible(true)
                    },
                    modifier = Modifier.alpha(if (uiState.isBusy) 0.38f else 1f),
                ) {
                    Icon(
                        Icons.Filled.Add,
                        contentDescription = stringResource(R.string.remote_vaults_add_cd),
                    )
                }
            },
        ) { innerPadding ->
            if (uiState.vaults.isEmpty()) {
                Text(
                    text = stringResource(R.string.remote_vaults_empty_hint),
                    modifier = Modifier
                        .padding(innerPadding)
                        .padding(24.dp),
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    items(uiState.vaults, key = { it.uuid }) { item ->
                        ElevatedCard(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable(
                                    enabled = !uiState.isBusy,
                                    interactionSource = remember { MutableInteractionSource() },
                                    indication = null,
                                ) { onOpenVault(item) },
                            shape = RoundedCornerShape(16.dp),
                            elevation = CardDefaults.elevatedCardElevation(defaultElevation = 2.dp),
                            colors = CardDefaults.elevatedCardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
                            ),
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.SpaceBetween,
                            ) {
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(
                                        text = item.label,
                                        style = MaterialTheme.typography.titleMedium,
                                        color = MaterialTheme.colorScheme.onSurface,
                                    )
                                    Spacer(modifier = Modifier.height(4.dp))
                                    Text(
                                        text = when (item.brand) {
                                            CloudBrand.YANDEX ->
                                                stringResource(R.string.remote_vault_type_yandex)
                                        },
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    )
                                    Spacer(modifier = Modifier.height(6.dp))
                                    if (!item.isAvailable) {
                                        Text(
                                            text = stringResource(R.string.remote_vault_unavailable),
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.error,
                                        )
                                        Spacer(modifier = Modifier.height(6.dp))
                                        FilledTonalButton(
                                            onClick = { viewModel.retryVault(item.uuid) },
                                            enabled = !uiState.isBusy,
                                        ) {
                                            Text(
                                                if (item.isRefreshing) {
                                                    stringResource(R.string.remote_vault_retrying)
                                                } else {
                                                    stringResource(R.string.remote_vault_retry_action)
                                                },
                                            )
                                        }
                                    }
                                }
                                IconButton(
                                    onClick = { viewModel.requestDeleteVault(item) },
                                    enabled = !uiState.isBusy,
                                ) {
                                    Icon(
                                        Icons.Filled.Delete,
                                        contentDescription = stringResource(R.string.remote_vault_delete_cd),
                                        tint = MaterialTheme.colorScheme.error,
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }

        if (uiState.isBusy) {
            CircularProgressIndicator(
                modifier = Modifier
                    .align(Alignment.Center)
                    .padding(24.dp),
            )
        }
    }

    if (uiState.addChoiceVisible) {
        Dialog(
            onDismissRequest = { if (!uiState.isBusy) viewModel.setAddChoiceVisible(false) },
        ) {
            Surface(
                shape = RoundedCornerShape(28.dp),
                color = MaterialTheme.colorScheme.surfaceContainerHigh,
                tonalElevation = 3.dp,
            ) {
                Column(
                    modifier = Modifier
                        .padding(24.dp)
                        .fillMaxWidth(),
                ) {
                    Text(
                        text = stringResource(R.string.remote_vaults_add_title),
                        style = MaterialTheme.typography.headlineSmall,
                        color = MaterialTheme.colorScheme.onSurface,
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    Text(
                        text = stringResource(R.string.remote_vaults_add_pick_provider),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    FilledTonalButton(
                        onClick = {
                            viewModel.setAddChoiceVisible(false)
                            viewModel.remoteAuthenticator.beginLink(CloudBrand.YANDEX) { outcome ->
                                when (outcome) {
                                    is VaultLinkOutcome.Success ->
                                        viewModel.onLinkSucceeded(outcome.registration)
                                    is VaultLinkOutcome.Failed -> {
                                        val notification = outcome.reason.toUserNotification()
                                        val text = if (notification.formatArgs.isEmpty()) {
                                            resources.getString(notification.id)
                                        } else {
                                            resources.getString(
                                                notification.id,
                                                *notification.formatArgs.toTypedArray(),
                                            )
                                        }
                                        Toast.makeText(context, text, Toast.LENGTH_LONG).show()
                                    }
                                    VaultLinkOutcome.Cancelled -> { }
                                }
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !uiState.isBusy,
                    ) {
                        Text(stringResource(R.string.remote_vaults_provider_yandex))
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End,
                    ) {
                        Text(
                            text = stringResource(R.string.remote_vaults_add_cancel),
                            style = MaterialTheme.typography.labelLarge,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier
                                .clickable(
                                    enabled = !uiState.isBusy,
                                    interactionSource = remember { MutableInteractionSource() },
                                    indication = null,
                                ) { viewModel.setAddChoiceVisible(false) }
                                .padding(vertical = 8.dp, horizontal = 4.dp),
                        )
                    }
                }
            }
        }
    }

    uiState.vaultPendingDelete?.let { pending ->
        AlertDialog(
            onDismissRequest = { if (!uiState.isBusy) viewModel.dismissDeleteVault() },
            title = {
                Text(stringResource(R.string.remote_vault_remove_title))
            },
            text = {
                Text(stringResource(R.string.remote_vault_remove_message, pending.label))
            },
            confirmButton = {
                TextButton(
                    onClick = { viewModel.confirmDeleteVault() },
                    enabled = !uiState.isBusy,
                ) {
                    Text(stringResource(R.string.remove))
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { viewModel.dismissDeleteVault() },
                    enabled = !uiState.isBusy,
                ) {
                    Text(stringResource(R.string.remote_vaults_add_cancel))
                }
            },
        )
    }
}
