package com.github.nullptroma.wallenc.ui.screens.main.screens.storage.secrets

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.github.nullptroma.wallenc.domain.datatypes.TextSecretEntryRecord
import com.github.nullptroma.wallenc.ui.R
import com.github.nullptroma.wallenc.ui.elements.WallencScreenContentPadding
import com.github.nullptroma.wallenc.ui.elements.WallencScreenScaffold
import com.github.nullptroma.wallenc.ui.resources.resolveText

@Composable
fun TextSecretEditScreen(
    modifier: Modifier = Modifier,
    viewModel: TextSecretEditViewModel = hiltViewModel(),
    onSaved: (String) -> Unit,
) {
    val uiState by viewModel.state.collectAsStateWithLifecycle()
    val currentOnSaved by rememberUpdatedState(onSaved)
    val inputEnabled = uiState.isAvailable && !uiState.isMutating && uiState.errorNotification == null

    var title by remember(uiState.initialSecret) {
        mutableStateOf(uiState.initialSecret?.title.orEmpty())
    }
    val items = remember(uiState.initialSecret) {
        mutableStateListOf<TextSecretEntryRecord>().apply {
            addAll(
                uiState.initialSecret?.items.orEmpty().ifEmpty {
                    listOf(TextSecretEntryRecord(label = null, value = ""))
                },
            )
        }
    }

    WallencScreenScaffold(modifier = modifier) { innerPadding ->
        WallencScreenContentPadding(innerPadding) {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Text(
                if (uiState.initialSecret == null) {
                    stringResource(R.string.text_secret_create)
                } else {
                    stringResource(R.string.text_secret_edit)
                },
            )
            uiState.errorNotification?.let { notification ->
                Text(text = notification.resolveText())
            }
            if (uiState.isMutating) {
                LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
            }
            OutlinedTextField(
                value = title,
                onValueChange = { title = it },
                enabled = inputEnabled,
                modifier = Modifier.fillMaxWidth(),
                label = { Text(stringResource(R.string.text_secret_title)) },
            )

            LazyColumn(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                itemsIndexed(items) { index, item ->
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                    ) {
                        OutlinedTextField(
                            value = item.label.orEmpty(),
                            onValueChange = { newLabel ->
                                items[index] = item.copy(label = newLabel.ifBlank { null })
                            },
                            enabled = inputEnabled,
                            modifier = Modifier.weight(0.45f),
                            label = { Text(stringResource(R.string.text_secret_item_label_optional)) },
                        )
                        OutlinedTextField(
                            value = item.value,
                            onValueChange = { newValue ->
                                items[index] = item.copy(value = newValue)
                            },
                            enabled = inputEnabled,
                            modifier = Modifier.weight(0.55f),
                            label = { Text(stringResource(R.string.text_secret_item_value)) },
                        )
                        IconButton(
                            enabled = inputEnabled,
                            onClick = {
                                if (items.size > 1) {
                                    items.removeAt(index)
                                } else {
                                    items[index] = TextSecretEntryRecord(label = null, value = "")
                                }
                            },
                        ) {
                            Icon(Icons.Default.Delete, contentDescription = stringResource(R.string.remove))
                        }
                    }
                }
            }

            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                TextButton(
                    onClick = { items.add(TextSecretEntryRecord(label = null, value = "")) },
                    enabled = inputEnabled,
                ) {
                    Icon(Icons.Default.Add, contentDescription = null)
                    Text(stringResource(R.string.text_secret_add_item))
                }
                TextButton(
                    onClick = {
                        viewModel.save(
                            title = title,
                            items = items.toList(),
                            onSaved = currentOnSaved,
                        )
                    },
                    enabled = title.isNotBlank() && inputEnabled,
                ) {
                    Text(stringResource(R.string.save))
                }
            }
        }
        }
    }
}
