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.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
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.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 ForgotPasswordScreen(
    onNavigateBack: () -> Unit,
    onNavigateToVerify: () -> Unit,
    onNavigateToReset: () -> Unit = {},
    viewModel: PasswordResetViewModel
) {
    var email by remember { mutableStateOf("") }
    val forgotPasswordState by viewModel.forgotPasswordState.collectAsStateWithLifecycle()
    val currentStep by viewModel.currentStep.collectAsStateWithLifecycle()

    // Handle errors for forgot password
    forgotPasswordState.HandleErrors(
        onRetry = {
            viewModel.setEmail(email)
            viewModel.requestPasswordReset(email)
        },
        errorTitle = "Failed to Send Reset Code"
    )

    // Handle automatic navigation to next step
    LaunchedEffect(currentStep) {
        when (currentStep) {
            com.tt.honeyDue.viewmodel.PasswordResetStep.VERIFY_CODE -> onNavigateToVerify()
            com.tt.honeyDue.viewmodel.PasswordResetStep.RESET_PASSWORD -> onNavigateToReset()
            else -> {}
        }
    }

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

    val isLoading = forgotPasswordState is ApiResult.Loading
    val isSuccess = forgotPasswordState is ApiResult.Success

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.auth_forgot_title)) },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        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 = 0
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(OrganicSpacing.spacious),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                    ) {
                        OrganicIconContainer(
                            icon = Icons.Default.Key,
                            size = 80.dp,
                            iconScale = 0.5f,
                            backgroundColor = MaterialTheme.colorScheme.primary,
                            iconColor = MaterialTheme.colorScheme.onPrimary
                        )

                        Text(
                            text = stringResource(Res.string.auth_forgot_title),
                            style = MaterialTheme.typography.headlineMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.textPrimary,
                            textAlign = TextAlign.Center
                        )

                        Text(
                            text = stringResource(Res.string.auth_forgot_subtitle),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.textSecondary,
                            textAlign = TextAlign.Center
                        )

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

                        OutlinedTextField(
                            value = email,
                            onValueChange = {
                                email = it
                                viewModel.resetForgotPasswordState()
                            },
                            label = { Text(stringResource(Res.string.auth_forgot_email_label)) },
                            leadingIcon = {
                                Icon(Icons.Default.Email, contentDescription = null) // decorative
                            },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            enabled = !isLoading
                        )

                        Text(
                            "We'll send a 6-digit verification code to this address",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.textSecondary,
                            textAlign = TextAlign.Center
                        )

                        ErrorCard(message = errorMessage)

                        if (isSuccess) {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                accentColor = MaterialTheme.colorScheme.primary,
                                showBlob = false
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    Icon(
                                        Icons.Default.CheckCircle,
                                        contentDescription = "Success",
                                        tint = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        "Check your email for a 6-digit verification code",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.textPrimary
                                    )
                                }
                            }
                        }

                        OrganicDivider(
                            modifier = Modifier.fillMaxWidth()
                        )

                        OrganicPrimaryButton(
                            text = stringResource(Res.string.auth_forgot_button),
                            onClick = {
                                viewModel.setEmail(email)
                                viewModel.requestPasswordReset(email)
                            },
                            enabled = email.isNotEmpty() && !isLoading,
                            isLoading = isLoading
                        )

                        TextButton(
                            onClick = onNavigateBack,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(
                                "Remember your password? Back to Login",
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                }
            }
        }
    }
}
