package com.tt.honeyDue.ui.screens.onboarding

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
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.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.network.ApiResult
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.OnboardingViewModel
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@Composable
fun OnboardingVerifyEmailContent(
    viewModel: OnboardingViewModel,
    onVerified: () -> Unit
) {
    var code by remember { mutableStateOf("") }
    var localErrorMessage by remember { mutableStateOf<String?>(null) }

    val verifyState by viewModel.verifyEmailState.collectAsStateWithLifecycle()

    LaunchedEffect(verifyState) {
        when (verifyState) {
            is ApiResult.Success -> {
                viewModel.resetVerifyEmailState()
                onVerified()
            }
            is ApiResult.Error -> {
                localErrorMessage = (verifyState as ApiResult.Error).message
            }
            else -> {}
        }
    }

    // Auto-verify when 6 digits entered
    LaunchedEffect(code) {
        if (code.length == 6) {
            viewModel.verifyEmail(code)
        }
    }

    val isLoading = verifyState is ApiResult.Loading

    WarmGradientBackground(
        modifier = Modifier.fillMaxSize()
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .imePadding()
                .padding(horizontal = OrganicSpacing.xl),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.weight(1f))

            // Header
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.lg)
            ) {
                // Icon with OrganicIconContainer
                OrganicIconContainer(
                    icon = Icons.Default.MarkEmailRead,
                    size = 100.dp,
                    iconSize = 50.dp,
                    contentDescription = null // decorative
                )

                // Title and subtitle
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                ) {
                    Text(
                        text = stringResource(Res.string.onboarding_verify_email_title),
                        style = MaterialTheme.typography.headlineMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onBackground
                    )

                    Text(
                        text = stringResource(Res.string.onboarding_verify_email_subtitle),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center
                    )
                }
            }

            Spacer(modifier = Modifier.height(OrganicSpacing.xl * 2))

            // Code input
            OutlinedTextField(
                value = code,
                onValueChange = {
                    if (it.length <= 6 && it.all { char -> char.isDigit() }) {
                        code = it
                        localErrorMessage = null
                    }
                },
                placeholder = {
                    Text(
                        "000000",
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f),
                        textAlign = TextAlign.Center,
                        modifier = Modifier.fillMaxWidth()
                    )
                },
                leadingIcon = {
                    Icon(Icons.Default.Pin, contentDescription = null) // decorative
                },
                modifier = Modifier.fillMaxWidth(),
                textStyle = LocalTextStyle.current.copy(
                    textAlign = TextAlign.Center,
                    fontWeight = FontWeight.Bold
                ),
                shape = RoundedCornerShape(OrganicRadius.md),
                singleLine = true,
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                enabled = !isLoading
            )

            // Error message
            if (localErrorMessage != null) {
                Spacer(modifier = Modifier.height(OrganicSpacing.md))
                OrganicCard(
                    modifier = Modifier.fillMaxWidth(),
                    accentColor = MaterialTheme.colorScheme.error,
                    showBlob = false
                ) {
                    Row(
                        modifier = Modifier.padding(OrganicSpacing.md),
                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Error,
                            contentDescription = "Error",
                            tint = MaterialTheme.colorScheme.error
                        )
                        Text(
                            text = localErrorMessage ?: "",
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }

            // Loading indicator
            if (isLoading) {
                Spacer(modifier = Modifier.height(OrganicSpacing.md))
                Row(
                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        strokeWidth = 2.dp
                    )
                    Text(
                        text = "Verifying...",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

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

            // Hint text
            Text(
                text = stringResource(Res.string.onboarding_verify_email_hint),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                textAlign = TextAlign.Center
            )

            Spacer(modifier = Modifier.weight(1f))

            // Verify button
            OrganicPrimaryButton(
                text = stringResource(Res.string.auth_verify_button),
                onClick = { viewModel.verifyEmail(code) },
                modifier = Modifier.fillMaxWidth(),
                enabled = code.length == 6 && !isLoading,
                isLoading = isLoading
            )

            Spacer(modifier = Modifier.height(OrganicSpacing.xl * 2))
        }
    }
}
