package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.support.enableTestTagsAsResourceId
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.ui.components.auth.AuthHeader
import com.tt.honeyDue.ui.components.auth.RequirementItem
import com.tt.honeyDue.ui.components.common.ErrorCard
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.AuthViewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegisterScreen(
    onRegisterSuccess: () -> Unit,
    onNavigateBack: () -> Unit,
    viewModel: AuthViewModel = viewModel { AuthViewModel() }
) {
    var username by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }

    val createState by viewModel.registerState.collectAsStateWithLifecycle()
    val focusManager = LocalFocusManager.current
    val usernameFocusRequester = remember { FocusRequester() }

    LaunchedEffect(Unit) {
        usernameFocusRequester.requestFocus()
    }

    // Handle errors for registration
    createState.HandleErrors(
        onRetry = { viewModel.register(username, email, password) },
        errorTitle = stringResource(Res.string.error_generic)
    )

    // Track screen view
    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.REGISTRATION_SCREEN_SHOWN)
    }

    LaunchedEffect(createState) {
        when (createState) {
            is ApiResult.Success -> {
                // Track successful registration
                val user = (createState as ApiResult.Success).data.user
                PostHogAnalytics.capture(AnalyticsEvents.USER_REGISTERED, mapOf("method" to "email"))
                PostHogAnalytics.identify(user.id.toString(), mapOf("email" to (user.email ?: ""), "username" to (user.username ?: "")))
                viewModel.resetRegisterState()
                onRegisterSuccess()
            }
            else -> {}
        }
    }

    WarmGradientBackground {
        Scaffold(
            modifier = Modifier.enableTestTagsAsResourceId(),
            topBar = {
                TopAppBar(
                    title = { Text(stringResource(Res.string.auth_register_title), fontWeight = FontWeight.SemiBold) },
                    navigationIcon = {
                        IconButton(
                            onClick = onNavigateBack,
                            modifier = Modifier.testTag(AccessibilityIds.Authentication.registerCancelButton)
                        ) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f)
                    )
                )
            },
            containerColor = androidx.compose.ui.graphics.Color.Transparent
        ) { paddingValues ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .imePadding()
                    .verticalScroll(rememberScrollState())
                    .padding(OrganicSpacing.xl),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.lg)
            ) {
                Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                AuthHeader(
                    icon = Icons.Default.PersonAdd,
                    title = stringResource(Res.string.auth_register_title),
                    subtitle = stringResource(Res.string.auth_register_subtitle)
                )

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

                OrganicCard(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                    ) {
                        OutlinedTextField(
                            value = username,
                            onValueChange = { username = it },
                            label = { Text(stringResource(Res.string.auth_register_username)) },
                            leadingIcon = {
                                Icon(Icons.Default.Person, contentDescription = null) // decorative
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .focusRequester(usernameFocusRequester)
                                .testTag(AccessibilityIds.Authentication.registerUsernameField),
                            singleLine = true,
                            shape = RoundedCornerShape(AppRadius.md),
                            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
                            keyboardActions = KeyboardActions(
                                onNext = { focusManager.moveFocus(FocusDirection.Down) }
                            )
                        )

                        OutlinedTextField(
                            value = email,
                            onValueChange = { email = it },
                            label = { Text(stringResource(Res.string.auth_register_email)) },
                            leadingIcon = {
                                Icon(Icons.Default.Email, contentDescription = null) // decorative
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .testTag(AccessibilityIds.Authentication.registerEmailField),
                            singleLine = true,
                            shape = RoundedCornerShape(AppRadius.md),
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Email,
                                imeAction = ImeAction.Next
                            ),
                            keyboardActions = KeyboardActions(
                                onNext = { focusManager.moveFocus(FocusDirection.Down) }
                            )
                        )

                        OrganicDivider()

                        OutlinedTextField(
                            value = password,
                            onValueChange = { password = it },
                            label = { Text(stringResource(Res.string.auth_register_password)) },
                            leadingIcon = {
                                Icon(Icons.Default.Lock, contentDescription = null) // decorative
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .testTag(AccessibilityIds.Authentication.registerPasswordField),
                            singleLine = true,
                            visualTransformation = PasswordVisualTransformation(),
                            shape = RoundedCornerShape(AppRadius.md),
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Password,
                                imeAction = ImeAction.Next
                            ),
                            keyboardActions = KeyboardActions(
                                onNext = { focusManager.moveFocus(FocusDirection.Down) }
                            )
                        )

                        OutlinedTextField(
                            value = confirmPassword,
                            onValueChange = { confirmPassword = it },
                            label = { Text(stringResource(Res.string.auth_register_confirm_password)) },
                            leadingIcon = {
                                Icon(Icons.Default.Lock, contentDescription = null) // decorative
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .testTag(AccessibilityIds.Authentication.registerConfirmPasswordField),
                            singleLine = true,
                            visualTransformation = PasswordVisualTransformation(),
                            shape = RoundedCornerShape(AppRadius.md),
                            keyboardOptions = KeyboardOptions(
                                keyboardType = KeyboardType.Password,
                                imeAction = ImeAction.Done
                            ),
                            keyboardActions = KeyboardActions(
                                onDone = { focusManager.clearFocus() }
                            )
                        )
                    }
                }

                // Password Requirements
                if (password.isNotEmpty()) {
                    val hasMinLength = password.length >= 8
                    val hasUppercase = password.any { it.isUpperCase() }
                    val hasLowercase = password.any { it.isLowerCase() }
                    val hasDigit = password.any { it.isDigit() }
                    val passwordsMatch = password.isNotEmpty() && password == confirmPassword

                    OrganicCard(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Column(
                            modifier = Modifier.padding(OrganicSpacing.md),
                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                        ) {
                            Text(
                                stringResource(Res.string.auth_password_requirements_title),
                                style = MaterialTheme.typography.bodyMedium,
                                fontWeight = FontWeight.SemiBold,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            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)
                        }
                    }
                }

                ErrorCard(
                    message = errorMessage,
                    modifier = Modifier.testTag(AccessibilityIds.Authentication.registerErrorMessage)
                )

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

                val passwordComplexityMessage = stringResource(Res.string.auth_password_complexity_error)
                val passwordsDontMatchMessage = stringResource(Res.string.auth_passwords_dont_match)

                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

                OrganicPrimaryButton(
                    text = stringResource(Res.string.auth_register_button),
                    onClick = {
                        when {
                            !isPasswordComplex -> {
                                errorMessage = passwordComplexityMessage
                            }
                            !passwordsMatch -> {
                                errorMessage = passwordsDontMatchMessage
                            }
                            else -> {
                                isLoading = true
                                errorMessage = ""
                                viewModel.register(username, email, password)
                            }
                        }
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Authentication.registerButton),
                    enabled = username.isNotEmpty() && email.isNotEmpty() &&
                             password.isNotEmpty() && isPasswordComplex && passwordsMatch && !isLoading,
                    isLoading = isLoading
                )

                Spacer(modifier = Modifier.height(OrganicSpacing.md))
            }
        }
    }
}
