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.KeyboardCapitalization
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 OnboardingJoinResidenceContent(
    viewModel: OnboardingViewModel,
    onJoined: () -> Unit
) {
    var shareCode by remember { mutableStateOf("") }
    var localErrorMessage by remember { mutableStateOf<String?>(null) }

    val joinState by viewModel.joinResidenceState.collectAsStateWithLifecycle()

    LaunchedEffect(joinState) {
        when (joinState) {
            is ApiResult.Success -> {
                onJoined()
            }
            is ApiResult.Error -> {
                localErrorMessage = (joinState as ApiResult.Error).message
            }
            else -> {}
        }
    }

    val isLoading = joinState is ApiResult.Loading
    val isCodeValid = shareCode.length == 6

    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
                OrganicIconContainer(
                    icon = Icons.Default.GroupAdd,
                    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_join_title),
                        style = MaterialTheme.typography.headlineMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onBackground
                    )

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

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

            // Share code input
            OutlinedTextField(
                value = shareCode,
                onValueChange = {
                    if (it.length <= 6) {
                        shareCode = it.uppercase()
                        localErrorMessage = null
                    }
                },
                placeholder = {
                    Text(
                        stringResource(Res.string.onboarding_join_placeholder),
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                    )
                },
                leadingIcon = {
                    Icon(Icons.Default.Key, contentDescription = null) // decorative
                },
                modifier = Modifier.fillMaxWidth(),
                textStyle = LocalTextStyle.current.copy(
                    textAlign = TextAlign.Center,
                    fontWeight = FontWeight.Bold
                ),
                shape = RoundedCornerShape(OrganicRadius.md),
                singleLine = true,
                keyboardOptions = KeyboardOptions(
                    capitalization = KeyboardCapitalization.Characters
                ),
                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 = "Joining residence...",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

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

            // Join button
            OrganicPrimaryButton(
                text = stringResource(Res.string.onboarding_join_button),
                onClick = { viewModel.joinResidence(shareCode) },
                modifier = Modifier.fillMaxWidth(),
                enabled = isCodeValid && !isLoading,
                isLoading = isLoading
            )

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