package com.tt.honeyDue.ui.screens.residence

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.PersonAdd
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.error
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.support.enableTestTagsAsResourceId
import com.tt.honeyDue.ui.components.common.StandardCard
import com.tt.honeyDue.ui.components.forms.FormTextField
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing

/**
 * Full-screen residence-join UI matching iOS
 * `iosApp/iosApp/Residence/JoinResidenceView.swift`.
 *
 * Replaces the legacy `JoinResidenceDialog`. The user enters a 6-character
 * invite code; on success [onJoined] is invoked with the newly joined
 * residence id so the caller can navigate to its detail screen. Errors
 * surface inline via the ViewModel and the screen stays mounted so the user
 * can retry without re-opening a sheet.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun JoinResidenceScreen(
    onNavigateBack: () -> Unit,
    onJoined: (Int) -> Unit,
    viewModel: JoinResidenceViewModel = viewModel { JoinResidenceViewModel() },
) {
    val code by viewModel.code.collectAsStateWithLifecycle()
    val error by viewModel.errorMessage.collectAsStateWithLifecycle()
    val submitState by viewModel.submitState.collectAsStateWithLifecycle()

    val isLoading = submitState is ApiResult.Loading

    // Navigate to the joined residence when submit transitions to Success.
    LaunchedEffect(submitState) {
        val s = submitState
        if (s is ApiResult.Success<Int>) {
            onJoined(s.data)
            viewModel.resetSubmitState()
        }
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "Join Property",
                        fontWeight = FontWeight.SemiBold,
                    )
                },
                navigationIcon = {
                    IconButton(
                        onClick = onNavigateBack,
                        enabled = !isLoading,
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface,
                ),
            )
        },
    ) { paddingValues: PaddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .imePadding()
                .padding(horizontal = AppSpacing.lg, vertical = AppSpacing.lg),
            verticalArrangement = Arrangement.spacedBy(AppSpacing.lg),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            // Hero
            Icon(
                imageVector = Icons.Default.PersonAdd,
                contentDescription = null, // decorative
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.size(72.dp),
            )
            Text(
                text = "Join a Shared Property",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground,
            )
            Text(
                text = "Enter the 6-character share code provided by the owner.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )

            StandardCard(
                modifier = Modifier.fillMaxWidth(),
            ) {
                FormTextField(
                    value = code,
                    onValueChange = { viewModel.updateCode(it) },
                    label = "Share Code",
                    modifier = Modifier.testTag(AccessibilityIds.Residence.joinShareCodeField),
                    placeholder = "ABC123",
                    enabled = !isLoading,
                    error = error,
                    helperText = if (error == null) "Codes are 6 uppercase characters" else null,
                    keyboardOptions = KeyboardOptions(
                        capitalization = KeyboardCapitalization.Characters,
                        keyboardType = KeyboardType.Ascii,
                    ),
                )

                if (error != null) {
                    Spacer(modifier = Modifier.height(AppSpacing.md))
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppSpacing.sm)
                            .semantics {
                                liveRegion = LiveRegionMode.Polite
                                error(error ?: "")
                            },
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = "Error",
                            tint = MaterialTheme.colorScheme.error,
                        )
                        Text(
                            text = error ?: "",
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodyMedium,
                        )
                    }
                }

                Spacer(modifier = Modifier.height(AppSpacing.md))

                Button(
                    onClick = { viewModel.submit() },
                    enabled = viewModel.canSubmit && !isLoading,
                    shape = RoundedCornerShape(AppRadius.md),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                    ),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.dp)
                        .testTag(AccessibilityIds.Residence.joinSubmitButton),
                ) {
                    if (isLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(22.dp),
                            color = MaterialTheme.colorScheme.onPrimary,
                            strokeWidth = 2.dp,
                        )
                        Spacer(modifier = Modifier.size(AppSpacing.sm))
                        Text(
                            text = "Joining…",
                            fontWeight = FontWeight.SemiBold,
                        )
                    } else {
                        Icon(
                            imageVector = Icons.Default.PersonAdd,
                            contentDescription = null, // decorative
                        )
                        Spacer(modifier = Modifier.size(AppSpacing.sm))
                        Text(
                            text = "Join Property",
                            fontWeight = FontWeight.SemiBold,
                        )
                    }
                }
            }

            Box(modifier = Modifier.fillMaxWidth())
        }
    }
}
