package net.buzzert.kordophonedroid.ui.settings

import android.provider.Settings
import androidx.annotation.DrawableRes
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
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.res.painterResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.hilt.navigation.compose.hiltViewModel
import net.buzzert.kordophonedroid.R
import net.buzzert.kordophonedroid.ui.LocalNavController
import net.buzzert.kordophonedroid.ui.theme.KordophoneTopAppBar

@Composable
fun SettingsScreen(
    viewModel: SettingsViewModel = hiltViewModel(),
) {
    val navController = LocalNavController.current
    Scaffold(
        topBar = {
            KordophoneTopAppBar(
                title = "Settings",
                backAction = { navController.popBackStack() },
            )
        },

    ) {
        SettingsFormView(
            viewModel = viewModel,
            modifier = Modifier
                .verticalScroll(rememberScrollState())
                .padding(it)
                .padding(6.dp)
        )
    }
}

@Composable
fun SettingsFormView(
    viewModel: SettingsViewModel,
    modifier: Modifier = Modifier
) {
    val serverName = viewModel.serverPreference.collectAsState()
    val userName = viewModel.usernamePreference.collectAsState()
    val password = viewModel.passwordPreference.collectAsState()

    Column(modifier) {
        var serverNameInput by remember { mutableStateOf(TextFieldValue(serverName.value)) }

        SettingsTextField(
            name = "Server",
            icon = R.drawable.storage,
            state = serverName,
            onSave = { viewModel.saveServerPreference(serverNameInput.text) }
        ) { state ->
            TextField(serverNameInput, onValueChange = {
                serverNameInput = it
            })
        }

        var usernameInput by remember { mutableStateOf(TextFieldValue(userName.value)) }
        var passwordInput by remember { mutableStateOf(TextFieldValue(password.value)) }
        SettingsTextField(
            name = "Authentication",
            icon = R.drawable.account_circle,
            state = userName,
            onSave = {
                viewModel.saveAuthenticationPreferences(usernameInput.text, passwordInput.text)
            }
        ) {
            Column() {
                TextField(
                    value = usernameInput,
                    onValueChange = { usernameInput = it },
                    label = { Text("Username") },
                )

                TextField(
                    value = passwordInput,
                    onValueChange = { passwordInput = it },
                    label = {Text("Password") },
                    visualTransformation = PasswordVisualTransformation(),
                )
            }
        }
    }
}

@Composable
@OptIn(ExperimentalMaterialApi::class)
fun <T> SettingsTextField(
    name: String,
    @DrawableRes icon: Int,
    state: State<T>,
    onSave: () -> Unit,
    dialogContent: @Composable (State<T>) -> Unit,
) {
    var showingDialog by remember { mutableStateOf(false) }

    if (showingDialog) {
        Dialog(
            onDismissRequest = { showingDialog = false }
        ) {
            EditDialog(
                name = name,
                onDismiss = {
                    onSave()
                    showingDialog = false
                },
                content = { dialogContent(state) }
            )
        }
    }

    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
        ,
        onClick = {
            showingDialog = true
        },
    ) {
        val valueString = state.value.toString().ifEmpty { "(Not set)" }

        Column {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Start,
                modifier = Modifier.padding(vertical = 8.dp)
            ) {
                Icon(
                    painterResource(id = icon),
                    contentDescription = "",
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(16.dp))
                Column(modifier = Modifier.padding(8.dp)) {
                    // Title
                    Text(
                        text = name,
                        style = MaterialTheme.typography.body1,
                        textAlign = TextAlign.Start,
                    )

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

                    // Value
                    Text(
                        text = valueString,
                        style = MaterialTheme.typography.body2,
                        textAlign = TextAlign.Start,
                        color = MaterialTheme.colors.onSurface.copy(alpha = 0.5f),
                    )
                }
            }

            Divider()
        }
    }
}

@Composable
private fun EditDialog(
    name: String,
    onDismiss: () -> Unit,
    content: @Composable () -> Unit,
) {
    Surface() {
        Column(
            modifier = Modifier
                .wrapContentHeight()
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(name)

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

            content()

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

            Row {
                Spacer(modifier = Modifier.weight(1f))
                Button(onClick = {
                    onDismiss()
                }) {
                    Text("Save")
                }
            }
        }
    }
}
