package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
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.text.input.VisualTransformation
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.GoogleSignInButton
import com.tt.honeyDue.ui.components.common.ErrorCard
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 com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@Composable
fun LoginScreen(
    onLoginSuccess: (com.tt.honeyDue.models.User) -> Unit,
    onNavigateToRegister: () -> Unit,
    onNavigateToForgotPassword: () -> Unit = {},
    viewModel: AuthViewModel = viewModel { AuthViewModel() }
) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var passwordVisible by remember { mutableStateOf(false) }
    var googleSignInError by remember { mutableStateOf<String?>(null) }
    val loginState by viewModel.loginState.collectAsStateWithLifecycle()
    val googleSignInState by viewModel.googleSignInState.collectAsStateWithLifecycle()
    val focusManager = LocalFocusManager.current
    val usernameFocusRequester = remember { FocusRequester() }

    LaunchedEffect(Unit) {
        usernameFocusRequester.requestFocus()
    }

    // Handle errors for login
    loginState.HandleErrors(
        onRetry = { viewModel.login(username, password) },
        errorTitle = stringResource(Res.string.auth_login_failed)
    )

    // Handle login state changes
    LaunchedEffect(loginState) {
        when (loginState) {
            is ApiResult.Success -> {
                val user = (loginState as ApiResult.Success).data.user
                // Track successful login
                PostHogAnalytics.capture(AnalyticsEvents.USER_SIGNED_IN, mapOf("method" to "email"))
                PostHogAnalytics.identify(user.id.toString(), mapOf("email" to (user.email ?: ""), "username" to (user.username ?: "")))
                onLoginSuccess(user)
            }
            else -> {}
        }
    }

    // Handle Google Sign In state changes
    LaunchedEffect(googleSignInState) {
        when (googleSignInState) {
            is ApiResult.Success -> {
                val response = (googleSignInState as ApiResult.Success).data
                // Track successful Google sign in
                PostHogAnalytics.capture(AnalyticsEvents.USER_SIGNED_IN, mapOf("method" to "google", "is_new_user" to response.isNewUser))
                PostHogAnalytics.identify(response.user.id.toString(), mapOf("email" to (response.user.email ?: ""), "username" to (response.user.username ?: "")))
                viewModel.resetGoogleSignInState()
                onLoginSuccess(response.user)
            }
            is ApiResult.Error -> {
                googleSignInError = com.tt.honeyDue.util.ErrorMessageParser.parse((googleSignInState as ApiResult.Error).message)
                viewModel.resetGoogleSignInState()
            }
            else -> {}
        }
    }

    val errorMessage = when {
        loginState is ApiResult.Error -> com.tt.honeyDue.util.ErrorMessageParser.parse((loginState as ApiResult.Error).message)
        googleSignInError != null -> googleSignInError ?: ""
        else -> ""
    }

    val isLoading = loginState is ApiResult.Loading || googleSignInState is ApiResult.Loading

    WarmGradientBackground {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .imePadding()
                .enableTestTagsAsResourceId(),
            contentAlignment = Alignment.Center
        ) {
            OrganicCard(
                modifier = Modifier
                    .fillMaxWidth(0.9f)
                    .wrapContentHeight(),
                showBlob = true,
                blobVariation = 0
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(OrganicSpacing.xxl),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.lg)
                ) {
                    AuthHeader(
                        icon = Icons.Default.Home,
                        title = stringResource(Res.string.app_name),
                        subtitle = stringResource(Res.string.app_tagline)
                    )

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

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

                    OutlinedTextField(
                        value = password,
                        onValueChange = { password = it },
                        label = { Text(stringResource(Res.string.auth_login_password_label)) },
                        leadingIcon = {
                            Icon(Icons.Default.Lock, contentDescription = null) // decorative
                        },
                        trailingIcon = {
                            IconButton(
                                onClick = { passwordVisible = !passwordVisible },
                                modifier = Modifier.testTag(AccessibilityIds.Authentication.passwordVisibilityToggle)
                            ) {
                                Icon(
                                    imageVector = if (passwordVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
                                    contentDescription = if (passwordVisible) stringResource(Res.string.auth_hide_password) else stringResource(Res.string.auth_show_password)
                                )
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Authentication.passwordField),
                        singleLine = true,
                        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                        shape = RoundedCornerShape(OrganicRadius.md),
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Password,
                            imeAction = ImeAction.Done
                        ),
                        keyboardActions = KeyboardActions(
                            onDone = {
                                focusManager.clearFocus()
                                if (username.isNotEmpty() && password.isNotEmpty()) {
                                    viewModel.login(username, password)
                                }
                            }
                        )
                    )

                    ErrorCard(message = errorMessage)

                    // Clear Google error when user starts typing
                    LaunchedEffect(username, password) {
                        googleSignInError = null
                    }

                    // Organic Primary Button
                    OrganicPrimaryButton(
                        text = stringResource(Res.string.auth_login_button),
                        onClick = {
                            viewModel.login(username, password)
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Authentication.loginButton),
                        enabled = username.isNotEmpty() && password.isNotEmpty(),
                        isLoading = isLoading
                    )

                    // Divider with "or"
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        OrganicDivider(
                            modifier = Modifier.weight(1f)
                        )
                        Text(
                            text = "or",
                            modifier = Modifier.padding(horizontal = OrganicSpacing.lg),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        OrganicDivider(
                            modifier = Modifier.weight(1f)
                        )
                    }

                    // Google Sign In button (only shows on Android)
                    GoogleSignInButton(
                        onSignInStarted = {
                            googleSignInError = null
                        },
                        onSignInSuccess = { idToken ->
                            viewModel.googleSignIn(idToken)
                        },
                        onSignInError = { error ->
                            googleSignInError = error
                        },
                        enabled = !isLoading
                    )

                    TextButton(
                        onClick = onNavigateToForgotPassword,
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Authentication.forgotPasswordButton)
                    ) {
                        Text(
                            stringResource(Res.string.auth_forgot_password),
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                    }

                    TextButton(
                        onClick = onNavigateToRegister,
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Authentication.signUpButton)
                    ) {
                        Text(
                            stringResource(Res.string.auth_no_account),
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                }
            }
        }
    }
}
