package de.lelehier.keeper.screens

import KeeperLargeFontFamily
import android.print.PrintAttributes.Margins
import android.util.Patterns
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.EaseIn
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun homeScreen(paddingValues: PaddingValues) {
    var currentScreen by rememberSaveable { mutableStateOf(0) }
    var nextScreen by rememberSaveable { mutableStateOf(1) }
    var serverURL by rememberSaveable { mutableStateOf("") }
    var username by rememberSaveable { mutableStateOf("") }
    var password by rememberSaveable { mutableStateOf("") }
    var apiKey by rememberSaveable { mutableStateOf("") }

    Column (
        modifier = Modifier
            .padding(paddingValues)
            .fillMaxSize()
            .imePadding(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center) {
        Greeting(serverURL, currentScreen);
        AnimatedContent(
            targetState = currentScreen,
            transitionSpec = {
                fadeIn(
                    animationSpec = tween(250)
                ) togetherWith fadeOut(animationSpec = tween(250))
            },

        ) { targetState -> when(targetState) {
            0 -> serverDialog(serverURL, {newServerURL -> serverURL = newServerURL })
            1 -> passwordDialog(username, password, {newUsername ->  username = newUsername}, {newPassword -> password = newPassword  })
        }
        }

        Button(
            onClick = {currentScreen = nextScreen},
            modifier = Modifier.padding(top = 24.dp),
            enabled = when(currentScreen) {
                0 -> isValidUrl(serverURL)
                1 -> username.isNotEmpty() && password.isNotEmpty()
                else -> false
            },
            ) {
            Row() {
                Text(text = "Next")
            }
        }
    }
}

@Composable
fun Greeting(serverURL: String, currentScreen: Int) {
    Column (horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(bottom = 24.dp)) {
        AnimatedVisibility (currentScreen == 0) {
            Text(
                text = "Welcome to",
                style = MaterialTheme.typography.headlineLarge,
                textAlign = TextAlign.Center
            )
        }
        Text(
            text = "Keeper",
            style = TextStyle(
                fontSize = 72.sp,
                fontFamily = KeeperLargeFontFamily,
                brush = Brush.linearGradient(listOf(MaterialTheme.colorScheme.onPrimaryContainer, MaterialTheme.colorScheme.onSecondaryContainer))),
            textAlign = TextAlign.Center,
        )
        AnimatedVisibility(currentScreen != 0) {
            Text(
                text = "@$serverURL",
                style = MaterialTheme.typography.titleSmall,
                textAlign = TextAlign.Center
            )
        }

    }
}


@Composable
fun serverDialog(serverURL: String, updateServerURL: (newServerURL: String) -> Unit) {
    var serverURL by remember { mutableStateOf("") }
    OutlinedTextField(
        label = { Text(text = "Server URL") },
        textStyle = MaterialTheme.typography.bodySmall,
        value = serverURL,
        onValueChange = { text ->
            serverURL = text
            updateServerURL(serverURL)
        },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
        supportingText = {
                AnimatedVisibility(!isValidUrl(serverURL) && serverURL != "") {
                    Text(
                        text = "No valid URL",
                        color = MaterialTheme.colorScheme.error
                    )
                }
        }
    )
}

fun isValidUrl(url: String): Boolean {
    return try {
        // Use Android's Patterns.WEB_URL for robust URL validation
        // This handles various URL formats, including those without schemes.
        Patterns.WEB_URL.matcher(url).matches()
    } catch (e: Exception) {
        false
    }
}

@Composable
fun passwordDialog(username: String, password: String, updateUsername: (newUsername: String) -> Unit, updatePassword: (newPassword: String) -> Unit) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    Column {
        OutlinedTextField(
            label = { Text(text = "Username") },
            textStyle = MaterialTheme.typography.bodySmall,
            value = username,
            onValueChange = { text ->
                username = text
                updateUsername(username)
            });
        OutlinedTextField(
            label = { Text(text = "Password") },
            textStyle = MaterialTheme.typography.bodySmall,
            value = password,
            onValueChange = { text ->
                password = text
                updatePassword(password)
            }
        )

    }
}