package eu.geyskens.pdfscan.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.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import eu.geyskens.pdfscan.R
import eu.geyskens.pdfscan.ScanViewModel
import eu.geyskens.pdfscan.data.ScanFilter
import eu.geyskens.pdfscan.paperless.PaperlessClient
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(vm: ScanViewModel, navController: NavController) {
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    val settings by vm.settings.collectAsState()

    var url by remember { mutableStateOf(settings.paperlessUrl) }
    var token by remember { mutableStateOf(vm.currentToken().orEmpty()) }
    var testing by remember { mutableStateOf(false) }
    var testResult by remember { mutableStateOf<String?>(null) }
    val snackbarHostState = remember { SnackbarHostState() }

    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.settings)) },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
                    }
                },
            )
        },
    ) { padding ->
        Column(
            Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Text(stringResource(R.string.paperless_header), style = androidx.compose.material3.MaterialTheme.typography.titleMedium)

            OutlinedTextField(
                value = url,
                onValueChange = { url = it; testResult = null },
                label = { Text(stringResource(R.string.server_url_label)) },
                singleLine = true,
                modifier = Modifier.fillMaxWidth(),
            )
            OutlinedTextField(
                value = token,
                onValueChange = { token = it; testResult = null },
                label = { Text(stringResource(R.string.api_token_label)) },
                singleLine = true,
                visualTransformation = PasswordVisualTransformation(),
                modifier = Modifier.fillMaxWidth(),
            )
            if (url.startsWith("http://")) {
                Text(
                    stringResource(R.string.http_warning),
                    color = Color(0xFFB26A00),
                    style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                )
            }

            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedButton(
                    onClick = {
                        testing = true
                        testResult = null
                        scope.launch {
                            testResult = when (val r = vm.testPaperless(url, token)) {
                                is PaperlessClient.Result.Success -> context.getString(R.string.connection_ok)
                                is PaperlessClient.Result.Failure -> r.message
                                else -> context.getString(R.string.unexpected_response)
                            }
                            testing = false
                        }
                    },
                    enabled = !testing,
                    modifier = Modifier.weight(1f),
                ) { Text(stringResource(R.string.test_connection)) }

                Button(
                    onClick = {
                        scope.launch {
                            vm.savePaperless(url, token)
                            snackbarHostState.showSnackbar(context.getString(R.string.settings_saved))
                        }
                    },
                    modifier = Modifier.weight(1f),
                ) { Text(stringResource(R.string.save)) }
            }
            if (testing) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    CircularProgressIndicator(Modifier.width(20.dp))
                    Spacer(Modifier.width(8.dp))
                    Text(stringResource(R.string.testing))
                }
            }
            testResult?.let { Text(it, color = Color(0xFF1F6FEB)) }

            Text(
                stringResource(R.string.default_filter),
                style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
            )
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                FilterChip(
                    selected = settings.defaultFilter == ScanFilter.COLOR,
                    onClick = { scope.launch { vm.setDefaultFilter(ScanFilter.COLOR) } },
                    label = { Text(stringResource(R.string.filter_color)) },
                )
                FilterChip(
                    selected = settings.defaultFilter == ScanFilter.GRAYSCALE,
                    onClick = { scope.launch { vm.setDefaultFilter(ScanFilter.GRAYSCALE) } },
                    label = { Text(stringResource(R.string.filter_grayscale)) },
                )
                FilterChip(
                    selected = settings.defaultFilter == ScanFilter.BLACK_WHITE,
                    onClick = { scope.launch { vm.setDefaultFilter(ScanFilter.BLACK_WHITE) } },
                    label = { Text(stringResource(R.string.filter_bw)) },
                )
            }
        }
    }
}
