package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
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.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
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.viewmodel.PasswordResetViewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ResetPasswordScreen(
    onPasswordResetSuccess: () -> Unit,
    onNavigateBack: (() -> Unit)? = null,
    viewModel: PasswordResetViewModel
) {
    var newPassword by remember { mutableStateOf("") }
    var confirmPassword by remember { mutableStateOf("") }
    var newPasswordVisible by remember { mutableStateOf(false) }
    var confirmPasswordVisible by remember { mutableStateOf(false) }

    val resetPasswordState by viewModel.resetPasswordState.collectAsStateWithLifecycle()
    val loginState by viewModel.loginState.collectAsStateWithLifecycle()
    val currentStep by viewModel.currentStep.collectAsStateWithLifecycle()

    // Handle errors for password reset
    resetPasswordState.HandleErrors(
        onRetry = { viewModel.resetPassword(newPassword, confirmPassword) },
        errorTitle = "Password Reset Failed"
    )

    val errorMessage = when (resetPasswordState) {
        is ApiResult.Error -> com.tt.honeyDue.util.ErrorMessageParser.parse((resetPasswordState as ApiResult.Error).message)
        else -> ""
    }

    val isLoading = resetPasswordState is ApiResult.Loading
    val isLoggingIn = currentStep == com.tt.honeyDue.viewmodel.PasswordResetStep.LOGGING_IN
    val isSuccess = currentStep == com.tt.honeyDue.viewmodel.PasswordResetStep.SUCCESS

    // Password validation
    val hasMinLength = newPassword.length >= 8
    val hasUppercase = newPassword.any { it.isUpperCase() }
    val hasLowercase = newPassword.any { it.isLowerCase() }
    val hasNumber = newPassword.any { it.isDigit() }
    val passwordsMatch = newPassword.isNotEmpty() && newPassword == confirmPassword
    val isFormValid = hasMinLength && hasUppercase && hasLowercase && hasNumber && passwordsMatch

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.auth_reset_title)) },
                navigationIcon = {
                    // Hide back button while logging in
                    if (!isLoggingIn) {
                        onNavigateBack?.let { callback ->
                            IconButton(onClick = callback) {
                                Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                            }
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        WarmGradientBackground {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .imePadding(),
                contentAlignment = Alignment.Center
            ) {
                OrganicCard(
                    modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .wrapContentHeight(),
                    showBlob = true,
                    blobVariation = 2
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(OrganicSpacing.spacious),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                    ) {
                        if (isSuccess) {
                            // Success State
                            OrganicIconContainer(
                                icon = Icons.Default.CheckCircle,
                                size = 80.dp,
                                iconScale = 0.5f,
                                backgroundColor = MaterialTheme.colorScheme.primary,
                                iconColor = MaterialTheme.colorScheme.onPrimary
                            )

                            Text(
                                text = "Success!",
                                style = MaterialTheme.typography.headlineMedium,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.textPrimary,
                                textAlign = TextAlign.Center
                            )

                            Text(
                                text = "Your password has been reset successfully",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.textSecondary,
                                textAlign = TextAlign.Center
                            )

                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                accentColor = MaterialTheme.colorScheme.primary,
                                showBlob = false
                            ) {
                                Text(
                                    "You can now log in with your new password",
                                    modifier = Modifier.padding(OrganicSpacing.cozy),
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.textPrimary,
                                    textAlign = TextAlign.Center
                                )
                            }

                            OrganicDivider(
                                modifier = Modifier.fillMaxWidth()
                            )

                            OrganicPrimaryButton(
                                text = "Return to Login",
                                onClick = onPasswordResetSuccess
                            )
                        } else {
                            // Reset Password Form
                            OrganicIconContainer(
                                icon = Icons.Default.LockReset,
                                size = 80.dp,
                                iconScale = 0.5f,
                                backgroundColor = MaterialTheme.colorScheme.primary,
                                iconColor = MaterialTheme.colorScheme.onPrimary
                            )

                            Text(
                                text = "Set New Password",
                                style = MaterialTheme.typography.headlineMedium,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.textPrimary,
                                textAlign = TextAlign.Center
                            )

                            Text(
                                text = "Create a strong password to secure your account",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.textSecondary,
                                textAlign = TextAlign.Center
                            )

                            // Password Requirements
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                accentColor = MaterialTheme.colorScheme.secondary,
                                showBlob = false
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    Text(
                                        "Password Requirements",
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontWeight = FontWeight.SemiBold,
                                        color = MaterialTheme.colorScheme.textPrimary
                                    )

                                    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),
                                        hasNumber
                                    )
                                    RequirementItem(
                                        stringResource(Res.string.auth_password_requirement_match),
                                        passwordsMatch
                                    )
                                }
                            }

                            OutlinedTextField(
                                value = newPassword,
                                onValueChange = {
                                    newPassword = it
                                    viewModel.resetResetPasswordState()
                                },
                                label = { Text(stringResource(Res.string.auth_reset_new_password)) },
                                leadingIcon = {
                                    Icon(Icons.Default.Lock, contentDescription = null) // decorative
                                },
                                trailingIcon = {
                                    IconButton(onClick = { newPasswordVisible = !newPasswordVisible }) {
                                        Icon(
                                            if (newPasswordVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
                                            contentDescription = if (newPasswordVisible) "Hide password" else "Show password"
                                        )
                                    }
                                },
                                modifier = Modifier.fillMaxWidth(),
                                singleLine = true,
                                visualTransformation = if (newPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                                enabled = !isLoading
                            )

                            OutlinedTextField(
                                value = confirmPassword,
                                onValueChange = {
                                    confirmPassword = it
                                    viewModel.resetResetPasswordState()
                                },
                                label = { Text(stringResource(Res.string.auth_reset_confirm_password)) },
                                leadingIcon = {
                                    Icon(Icons.Default.Lock, contentDescription = null) // decorative
                                },
                                trailingIcon = {
                                    IconButton(onClick = { confirmPasswordVisible = !confirmPasswordVisible }) {
                                        Icon(
                                            if (confirmPasswordVisible) Icons.Default.Visibility else Icons.Default.VisibilityOff,
                                            contentDescription = if (confirmPasswordVisible) "Hide password" else "Show password"
                                        )
                                    }
                                },
                                modifier = Modifier.fillMaxWidth(),
                                singleLine = true,
                                visualTransformation = if (confirmPasswordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                                enabled = !isLoading
                            )

                            ErrorCard(message = errorMessage)

                            OrganicDivider(
                                modifier = Modifier.fillMaxWidth()
                            )

                            OrganicPrimaryButton(
                                text = if (isLoggingIn) "Logging in..." else stringResource(Res.string.auth_reset_button),
                                onClick = {
                                    viewModel.resetPassword(newPassword, confirmPassword)
                                },
                                enabled = isFormValid && !isLoading && !isLoggingIn,
                                isLoading = isLoading || isLoggingIn
                            )
                        }
                    }
                }
            }
        }
    }
}
