package com.tt.honeyDue.ui.screens.onboarding

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.error
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.components.auth.RequirementItem
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.OnboardingViewModel
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@Composable
fun OnboardingCreateAccountContent(
    viewModel: OnboardingViewModel,
    onAccountCreated: (Boolean) -> Unit // Boolean = isVerified
) {
    var username by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var isFormExpanded by remember { mutableStateOf(false) }
    var showLoginDialog by remember { mutableStateOf(false) }
    var localErrorMessage by remember { mutableStateOf<String?>(null) }

    val registerState by viewModel.registerState.collectAsStateWithLifecycle()

    LaunchedEffect(registerState) {
        when (registerState) {
            is ApiResult.Success -> {
                val user = (registerState as ApiResult.Success).data.user
                viewModel.resetRegisterState()
                onAccountCreated(user.verified)
            }
            is ApiResult.Error -> {
                localErrorMessage = (registerState as ApiResult.Error).message
            }
            else -> {}
        }
    }

    val isLoading = registerState is ApiResult.Loading
    val hasMinLength = password.length >= 8
    val hasUppercase = password.any { it.isUpperCase() }
    val hasLowercase = password.any { it.isLowerCase() }
    val hasDigit = password.any { it.isDigit() }
    val isPasswordComplex = hasMinLength && hasUppercase && hasLowercase && hasDigit
    val passwordsMatch = password.isNotEmpty() && password == confirmPassword
    val isFormValid = username.isNotBlank() &&
            email.isNotBlank() &&
            isPasswordComplex &&
            passwordsMatch

    WarmGradientBackground(
        modifier = Modifier.fillMaxSize()
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .imePadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = OrganicSpacing.xl)
        ) {
            Spacer(modifier = Modifier.height(OrganicSpacing.xl))

            // Header
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
            ) {
                // Icon
                OrganicIconContainer(
                    icon = Icons.Default.PersonAdd,
                    size = 80.dp,
                    iconSize = 40.dp,
                    contentDescription = null // decorative
                )

                Text(
                    text = stringResource(Res.string.onboarding_create_account_title),
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onBackground,
                    textAlign = TextAlign.Center
                )

                Text(
                    text = stringResource(Res.string.onboarding_create_account_subtitle),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    textAlign = TextAlign.Center
                )
            }

            Spacer(modifier = Modifier.height(OrganicSpacing.xl * 2))

            // Create with Email section
            if (!isFormExpanded) {
                // Collapsed state - show button
                Button(
                    onClick = { isFormExpanded = true },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.dp),
                    shape = RoundedCornerShape(OrganicRadius.md),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.1f),
                        contentColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Icon(Icons.Default.Email, contentDescription = null) // decorative
                    Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                    Text(
                        text = stringResource(Res.string.onboarding_create_with_email),
                        fontWeight = FontWeight.Medium
                    )
                }
            }

            // Expanded form
            AnimatedVisibility(
                visible = isFormExpanded,
                enter = fadeIn() + expandVertically(),
                exit = fadeOut() + shrinkVertically()
            ) {
                Column(
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                ) {
                    // Username
                    OutlinedTextField(
                        value = username,
                        onValueChange = {
                            username = it
                            localErrorMessage = null
                        },
                        label = { Text(stringResource(Res.string.auth_register_username)) },
                        leadingIcon = {
                            Icon(Icons.Default.Person, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        shape = RoundedCornerShape(OrganicRadius.md),
                        enabled = !isLoading
                    )

                    // Email
                    OutlinedTextField(
                        value = email,
                        onValueChange = {
                            email = it
                            localErrorMessage = null
                        },
                        label = { Text(stringResource(Res.string.auth_register_email)) },
                        leadingIcon = {
                            Icon(Icons.Default.Email, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        shape = RoundedCornerShape(OrganicRadius.md),
                        enabled = !isLoading
                    )

                    // Password
                    OutlinedTextField(
                        value = password,
                        onValueChange = {
                            password = it
                            localErrorMessage = null
                        },
                        label = { Text(stringResource(Res.string.auth_register_password)) },
                        leadingIcon = {
                            Icon(Icons.Default.Lock, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        visualTransformation = PasswordVisualTransformation(),
                        shape = RoundedCornerShape(OrganicRadius.md),
                        enabled = !isLoading
                    )

                    // Confirm Password
                    OutlinedTextField(
                        value = confirmPassword,
                        onValueChange = {
                            confirmPassword = it
                            localErrorMessage = null
                        },
                        label = { Text(stringResource(Res.string.auth_register_confirm_password)) },
                        leadingIcon = {
                            Icon(Icons.Default.Lock, contentDescription = null) // decorative
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        visualTransformation = PasswordVisualTransformation(),
                        shape = RoundedCornerShape(OrganicRadius.md),
                        enabled = !isLoading,
                        isError = confirmPassword.isNotEmpty() && password != confirmPassword,
                        supportingText = if (confirmPassword.isNotEmpty() && password != confirmPassword) {
                            { Text(stringResource(Res.string.auth_passwords_dont_match)) }
                        } else null
                    )

                    // Password Requirements
                    if (password.isNotEmpty()) {
                        Column(
                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                        ) {
                            Text(
                                stringResource(Res.string.auth_password_requirements_title),
                                style = MaterialTheme.typography.bodySmall,
                                fontWeight = FontWeight.SemiBold,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            RequirementItem(stringResource(Res.string.auth_password_requirement_length), hasMinLength)
                            RequirementItem(stringResource(Res.string.auth_password_requirement_uppercase), hasUppercase)
                            RequirementItem(stringResource(Res.string.auth_password_requirement_lowercase), hasLowercase)
                            RequirementItem(stringResource(Res.string.auth_password_requirement_digit), hasDigit)
                            RequirementItem(stringResource(Res.string.auth_password_requirement_match), passwordsMatch)
                        }
                    }

                    // Error message
                    if (localErrorMessage != null) {
                        OrganicCard(
                            modifier = Modifier
                                .fillMaxWidth()
                                .semantics {
                                    liveRegion = LiveRegionMode.Polite
                                    error(localErrorMessage ?: "")
                                },
                            accentColor = MaterialTheme.colorScheme.error,
                            showBlob = false
                        ) {
                            Row(
                                modifier = Modifier.padding(OrganicSpacing.md),
                                horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.Error,
                                    contentDescription = "Error",
                                    tint = MaterialTheme.colorScheme.error
                                )
                                Text(
                                    text = localErrorMessage ?: "",
                                    color = MaterialTheme.colorScheme.error,
                                    style = MaterialTheme.typography.bodySmall
                                )
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                    // Create Account button
                    OrganicPrimaryButton(
                        text = stringResource(Res.string.auth_register_button),
                        onClick = {
                            if (password == confirmPassword) {
                                viewModel.register(username, email, password)
                            } else {
                                localErrorMessage = "Passwords don't match"
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = isFormValid && !isLoading,
                        isLoading = isLoading
                    )
                }
            }

            Spacer(modifier = Modifier.height(OrganicSpacing.xl))

            // Already have an account
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(Res.string.auth_have_account).substringBefore("?") + "?",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                TextButton(onClick = { showLoginDialog = true }) {
                    Text(
                        text = stringResource(Res.string.auth_login_button),
                        fontWeight = FontWeight.SemiBold,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }

            Spacer(modifier = Modifier.height(OrganicSpacing.xl * 2))
        }
    }

    // Login dialog
    if (showLoginDialog) {
        OnboardingLoginDialog(
            viewModel = viewModel,
            onDismiss = { showLoginDialog = false },
            onLoginSuccess = { isVerified ->
                showLoginDialog = false
                onAccountCreated(isVerified)
            }
        )
    }
}

@Composable
private fun OnboardingLoginDialog(
    viewModel: OnboardingViewModel,
    onDismiss: () -> Unit,
    onLoginSuccess: (Boolean) -> Unit
) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    val loginState by viewModel.loginState.collectAsStateWithLifecycle()

    LaunchedEffect(loginState) {
        when (loginState) {
            is ApiResult.Success -> {
                val user = (loginState as ApiResult.Success).data.user
                viewModel.resetLoginState()
                onLoginSuccess(user.verified)
            }
            else -> {}
        }
    }

    val isLoading = loginState is ApiResult.Loading
    val errorMessage = when (loginState) {
        is ApiResult.Error -> (loginState as ApiResult.Error).message
        else -> null
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                stringResource(Res.string.auth_login_title),
                fontWeight = FontWeight.SemiBold
            )
        },
        text = {
            Column(
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
            ) {
                OutlinedTextField(
                    value = username,
                    onValueChange = { username = it },
                    label = { Text(stringResource(Res.string.auth_login_username_label)) },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(OrganicRadius.md),
                    enabled = !isLoading
                )

                OutlinedTextField(
                    value = password,
                    onValueChange = { password = it },
                    label = { Text(stringResource(Res.string.auth_login_password_label)) },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(OrganicRadius.md),
                    visualTransformation = PasswordVisualTransformation(),
                    enabled = !isLoading
                )

                if (errorMessage != null) {
                    Text(
                        text = errorMessage,
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
            }
        },
        confirmButton = {
            Button(
                onClick = { viewModel.login(username, password) },
                enabled = username.isNotEmpty() && password.isNotEmpty() && !isLoading
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text(stringResource(Res.string.auth_login_button))
                }
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(stringResource(Res.string.common_cancel))
            }
        }
    )
}
