package de.trainingstagebuch.app.ui.screens

import androidx.compose.foundation.layout.Arrangement
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
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.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.lifecycle.viewmodel.compose.viewModel
import de.trainingstagebuch.app.R
import de.trainingstagebuch.app.repository.MemberTransferSummary
import de.trainingstagebuch.app.ui.ErrorBanner
import de.trainingstagebuch.app.ui.ErrorSnackbarHost
import de.trainingstagebuch.app.ui.TrainingstagebuchTopBar
import de.trainingstagebuch.app.viewmodel.MemberTransferSettingsViewModel

@Composable
fun MemberTransferSettingsScreen(
    memberTransferViewModel: MemberTransferSettingsViewModel = viewModel()
) {
    val state by memberTransferViewModel.state.collectAsState()
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    var dismissedMessage by remember { mutableStateOf<de.trainingstagebuch.app.utils.UiText?>(null) }

    LaunchedEffect(state.message) {
        val message = state.message
        if (message != null) {
            dismissedMessage = null
            snackbarHostState.showSnackbar(message.resolve(context))
        }
    }

    Scaffold(
        topBar = { TrainingstagebuchTopBar(title = stringResource(R.string.member_transfer_title)) },
        snackbarHost = { ErrorSnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        if (state.loading) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                CircularProgressIndicator()
                Text(
                    text = stringResource(R.string.member_transfer_loading),
                    modifier = Modifier.padding(top = 12.dp)
                )
            }
            return@Scaffold
        }

        val message = state.message
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .verticalScroll(rememberScrollState())
                .padding(16.dp)
        ) {
            Text(
                text = stringResource(R.string.member_transfer_title),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            if (message != null && message != dismissedMessage) {
                ErrorBanner(
                    message = message.resolve(context),
                    onDismiss = { dismissedMessage = message },
                    modifier = Modifier.padding(bottom = 12.dp)
                )
            }

            OutlinedTextField(
                value = state.server,
                onValueChange = memberTransferViewModel::onServerChanged,
                label = { Text(stringResource(R.string.member_transfer_server_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.loginEndpoint,
                onValueChange = memberTransferViewModel::onLoginEndpointChanged,
                label = { Text(stringResource(R.string.member_transfer_login_endpoint_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.loginFormat,
                onValueChange = memberTransferViewModel::onLoginFormatChanged,
                label = { Text(stringResource(R.string.member_transfer_login_format_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.loginUsername,
                onValueChange = memberTransferViewModel::onLoginUsernameChanged,
                label = { Text(stringResource(R.string.member_transfer_login_username_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.loginPassword,
                onValueChange = memberTransferViewModel::onLoginPasswordChanged,
                label = { Text(stringResource(R.string.member_transfer_login_password_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.loginAdditionalField1,
                onValueChange = memberTransferViewModel::onLoginAdditionalField1Changed,
                label = { Text(stringResource(R.string.member_transfer_login_additional_1_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.loginAdditionalField2,
                onValueChange = memberTransferViewModel::onLoginAdditionalField2Changed,
                label = { Text(stringResource(R.string.member_transfer_login_additional_2_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(16.dp))

            OutlinedTextField(
                value = state.transferEndpoint,
                onValueChange = memberTransferViewModel::onTransferEndpointChanged,
                label = { Text(stringResource(R.string.member_transfer_endpoint_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.transferMethod,
                onValueChange = memberTransferViewModel::onTransferMethodChanged,
                label = { Text(stringResource(R.string.member_transfer_method_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.transferFormat,
                onValueChange = memberTransferViewModel::onTransferFormatChanged,
                label = { Text(stringResource(R.string.member_transfer_format_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(10.dp))

            OutlinedTextField(
                value = state.transferTemplate,
                onValueChange = memberTransferViewModel::onTransferTemplateChanged,
                label = { Text(stringResource(R.string.member_transfer_template_label)) },
                modifier = Modifier.fillMaxWidth(),
                minLines = 4,
                maxLines = 8
            )

            Spacer(modifier = Modifier.height(10.dp))

            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(R.string.member_transfer_bulk_mode_label),
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.weight(1f)
                )
                Switch(
                    checked = state.useBulkMode,
                    onCheckedChange = memberTransferViewModel::onUseBulkModeChanged
                )
            }

            if (state.useBulkMode) {
                Spacer(modifier = Modifier.height(10.dp))
                OutlinedTextField(
                    value = state.bulkWrapperTemplate,
                    onValueChange = memberTransferViewModel::onBulkWrapperTemplateChanged,
                    label = { Text(stringResource(R.string.member_transfer_bulk_wrapper_label)) },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 3,
                    maxLines = 6
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Button(
                    onClick = memberTransferViewModel::saveConfig,
                    enabled = !state.saving && !state.deleting && !state.transferring,
                    modifier = Modifier.weight(1f)
                ) {
                    if (state.saving) {
                        CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(vertical = 2.dp))
                    } else {
                        Text(stringResource(R.string.member_transfer_save_button))
                    }
                }

                TextButton(
                    onClick = memberTransferViewModel::deleteConfig,
                    enabled = !state.saving && !state.deleting && !state.transferring,
                    modifier = Modifier.weight(1f)
                ) {
                    if (state.deleting) {
                        CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(vertical = 2.dp))
                    } else {
                        Text(stringResource(R.string.member_transfer_delete_button))
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            Button(
                onClick = memberTransferViewModel::executeTransfer,
                enabled = !state.saving && !state.deleting && !state.transferring,
                modifier = Modifier.fillMaxWidth()
            ) {
                if (state.transferring) {
                    CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(vertical = 2.dp))
                } else {
                    Text(stringResource(R.string.member_transfer_execute_button))
                }
            }

            val summary = state.transferSummary
            if (summary != null) {
                Spacer(modifier = Modifier.height(16.dp))
                TransferSummaryCard(summary = summary)
            }

            Spacer(modifier = Modifier.height(20.dp))
        }
    }
}

@Composable
private fun TransferSummaryCard(summary: MemberTransferSummary) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
    ) {
        Column(modifier = Modifier.padding(12.dp)) {
            Text(
                text = stringResource(R.string.member_transfer_summary_title),
                style = MaterialTheme.typography.titleMedium
            )
            Text(
                text = stringResource(
                    R.string.member_transfer_summary_transferred,
                    summary.transferred,
                    summary.total
                ),
                modifier = Modifier.padding(top = 6.dp)
            )
            if (!summary.message.isNullOrBlank()) {
                Text(
                    text = summary.message,
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
            if (summary.invalidMembers.isNotEmpty()) {
                Text(
                    text = stringResource(
                        R.string.member_transfer_summary_invalid_members,
                        summary.invalidMembers.joinToString(", ")
                    ),
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
            if (summary.errors.isNotEmpty()) {
                Text(
                    text = stringResource(
                        R.string.member_transfer_summary_errors,
                        summary.errors.joinToString(" | ")
                    ),
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
        }
    }
}
