package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
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.KeyboardType
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.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 VerifyResetCodeScreen(
    onNavigateBack: () -> Unit,
    onNavigateToReset: () -> Unit,
    viewModel: PasswordResetViewModel
) {
    var code by remember { mutableStateOf("") }
    val email by viewModel.email.collectAsStateWithLifecycle()
    val verifyCodeState by viewModel.verifyCodeState.collectAsStateWithLifecycle()
    val currentStep by viewModel.currentStep.collectAsStateWithLifecycle()

    // Handle errors for code verification
    verifyCodeState.HandleErrors(
        onRetry = { viewModel.verifyResetCode(email, code) },
        errorTitle = "Code Verification Failed"
    )

    // Handle automatic navigation to next step
    LaunchedEffect(currentStep) {
        if (currentStep == com.tt.honeyDue.viewmodel.PasswordResetStep.RESET_PASSWORD) {
            onNavigateToReset()
        }
    }

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

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

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

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

                        Text(
                            text = "We sent a 6-digit code to",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.textSecondary,
                            textAlign = TextAlign.Center
                        )

                        Text(
                            email,
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.SemiBold,
                            color = MaterialTheme.colorScheme.textPrimary,
                            textAlign = TextAlign.Center
                        )

                        OrganicCard(
                            modifier = Modifier.fillMaxWidth(),
                            accentColor = MaterialTheme.colorScheme.secondary,
                            showBlob = false
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(OrganicSpacing.cozy),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                            ) {
                                Icon(
                                    Icons.Default.Timer,
                                    contentDescription = null, // decorative
                                    tint = MaterialTheme.colorScheme.secondary
                                )
                                Text(
                                    "Code expires in 15 minutes",
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.SemiBold,
                                    color = MaterialTheme.colorScheme.textPrimary
                                )
                            }
                        }

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

                        OutlinedTextField(
                            value = code,
                            onValueChange = {
                                if (it.length <= 6 && it.all { char -> char.isDigit() }) {
                                    code = it
                                    viewModel.resetVerifyCodeState()
                                }
                            },
                            label = { Text(stringResource(Res.string.auth_verify_code_label)) },
                            placeholder = { Text("000000") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                            enabled = !isLoading,
                            textStyle = MaterialTheme.typography.headlineMedium.copy(
                                fontWeight = FontWeight.Bold,
                                textAlign = TextAlign.Center
                            )
                        )

                        Text(
                            "Enter the 6-digit code from your email",
                            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 = "Verified",
                                        tint = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        "Code verified! Now set your new password",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.textPrimary
                                    )
                                }
                            }
                        }

                        OrganicDivider(
                            modifier = Modifier.fillMaxWidth()
                        )

                        OrganicPrimaryButton(
                            text = stringResource(Res.string.auth_verify_button),
                            onClick = {
                                viewModel.verifyResetCode(email, code)
                            },
                            enabled = code.length == 6 && !isLoading,
                            isLoading = isLoading
                        )

                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                        ) {
                            Text(
                                "Didn't receive the code?",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.textSecondary
                            )

                            TextButton(onClick = {
                                code = ""
                                viewModel.resetVerifyCodeState()
                                viewModel.moveToPreviousStep()
                                onNavigateBack()
                            }) {
                                Text(
                                    stringResource(Res.string.auth_verify_resend),
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }

                            Text(
                                "Check your spam folder if you don't see it",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.textSecondary,
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }
            }
        }
    }
}
