package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
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.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
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.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.common.ErrorCard
import com.tt.honeyDue.viewmodel.AuthViewModel
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 VerifyEmailScreen(
    onVerifySuccess: () -> Unit,
    onLogout: () -> Unit,
    viewModel: AuthViewModel = viewModel { AuthViewModel() }
) {
    var code by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }

    val verifyState by viewModel.verifyEmailState.collectAsStateWithLifecycle()

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

    LaunchedEffect(verifyState) {
        when (verifyState) {
            is ApiResult.Success -> {
                viewModel.resetVerifyEmailState()
                onVerifySuccess()
            }
            is ApiResult.Error -> {
                errorMessage = com.tt.honeyDue.util.ErrorMessageParser.parse((verifyState as ApiResult.Error).message)
                isLoading = false
            }
            is ApiResult.Loading -> {
                isLoading = true
                errorMessage = ""
            }
            is ApiResult.Idle -> {
                // Do nothing - initial state, no loading indicator needed
            }
            else -> {}
        }
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.auth_verify_title), fontWeight = FontWeight.SemiBold) },
                actions = {
                    TextButton(
                        onClick = onLogout,
                        modifier = Modifier.testTag(AccessibilityIds.Authentication.verificationLogoutButton)
                    ) {
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(4.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.Logout,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(18.dp)
                            )
                            Text(stringResource(Res.string.home_logout))
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        WarmGradientBackground {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .imePadding()
                    .verticalScroll(rememberScrollState())
                    .padding(OrganicSpacing.comfortable),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
            ) {
                Spacer(modifier = Modifier.height(OrganicSpacing.compact))

                OrganicIconContainer(
                    icon = Icons.Default.MarkEmailRead,
                    size = 80.dp,
                    iconScale = 0.5f,
                    backgroundColor = MaterialTheme.colorScheme.primary,
                    iconColor = MaterialTheme.colorScheme.onPrimary
                )

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

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

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

                OrganicCard(
                    modifier = Modifier.fillMaxWidth(),
                    accentColor = MaterialTheme.colorScheme.error,
                    showBlob = false
                ) {
                    Column(
                        modifier = Modifier.padding(OrganicSpacing.cozy),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                    ) {
                        Icon(
                            Icons.Default.Info,
                            contentDescription = "Info",
                            tint = MaterialTheme.colorScheme.error
                        )
                        Text(
                            text = "Email verification is required. Check your inbox for a 6-digit code.",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.textPrimary,
                            textAlign = TextAlign.Center,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                }

                OutlinedTextField(
                    value = code,
                    onValueChange = {
                        if (it.length <= 6 && it.all { char -> char.isDigit() }) {
                            code = it
                        }
                    },
                    label = { Text(stringResource(Res.string.auth_verify_code_label)) },
                    leadingIcon = {
                        Icon(Icons.Default.Pin, contentDescription = null) // decorative
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Authentication.verificationCodeField),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    placeholder = { Text("000000") }
                )

                if (errorMessage.isNotEmpty()) {
                    ErrorCard(
                        message = errorMessage
                    )
                }

                OrganicDivider(
                    modifier = Modifier.fillMaxWidth()
                )

                OrganicPrimaryButton(
                    text = stringResource(Res.string.auth_verify_button),
                    onClick = {
                        if (code.length == 6) {
                            isLoading = true
                            viewModel.verifyEmail(code)
                        } else {
                            errorMessage = "Please enter a valid 6-digit code"
                        }
                    },
                    modifier = Modifier.testTag(AccessibilityIds.Authentication.verifyButton),
                    enabled = !isLoading && code.length == 6,
                    isLoading = isLoading
                )

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

                Text(
                    text = "Didn't receive the code? Check your spam folder or contact support.",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.textSecondary,
                    textAlign = TextAlign.Center
                )
            }
        }
    }
}
