package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.platform.LocalClipboardManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import honeydue.composeapp.generated.resources.*
import com.tt.honeyDue.models.ResidenceUser
import com.tt.honeyDue.models.ResidenceShareCode
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.support.enableTestTagsAsResourceId
import com.tt.honeyDue.ui.components.common.StandardErrorState
import com.tt.honeyDue.ui.theme.*
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ManageUsersScreen(
    residenceId: Int,
    residenceName: String,
    isPrimaryOwner: Boolean,
    residenceOwnerId: Int,
    onNavigateBack: () -> Unit,
    onUserRemoved: () -> Unit = {},
    onSharePackage: () -> Unit = {}
) {
    var users by remember { mutableStateOf<List<ResidenceUser>>(emptyList()) }
    var shareCode by remember { mutableStateOf<ResidenceShareCode?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var error by remember { mutableStateOf<String?>(null) }
    var isGeneratingCode by remember { mutableStateOf(false) }
    var showRemoveConfirmation by remember { mutableStateOf<ResidenceUser?>(null) }

    val scope = rememberCoroutineScope()
    val clipboardManager = LocalClipboardManager.current
    val snackbarHostState = remember { SnackbarHostState() }

    // Extracted so retry can reuse it.
    suspend fun loadUsers() {
        isLoading = true
        error = null
        when (val result = APILayer.getResidenceUsers(residenceId)) {
            is ApiResult.Success -> {
                users = result.data
                isLoading = false
            }
            is ApiResult.Error -> {
                error = result.message
                isLoading = false
            }
            else -> {}
        }
    }

    LaunchedEffect(residenceId) {
        shareCode = null
        loadUsers()
    }

    WarmGradientBackground {
        Scaffold(
            modifier = Modifier.enableTestTagsAsResourceId(),
            containerColor = androidx.compose.ui.graphics.Color.Transparent,
            topBar = {
                TopAppBar(
                    title = {
                        Column {
                            Text(
                                stringResource(Res.string.manage_users_invite_title),
                                fontWeight = FontWeight.SemiBold
                            )
                            Text(
                                residenceName,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    },
                    navigationIcon = {
                        IconButton(onClick = onNavigateBack) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = androidx.compose.ui.graphics.Color.Transparent
                    )
                )
            },
            snackbarHost = { SnackbarHost(snackbarHostState) }
        ) { paddingValues ->
            if (isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (error != null) {
                StandardErrorState(
                    title = "Couldn't load users",
                    message = error ?: "Unknown error",
                    onRetry = { scope.launch { loadUsers() } },
                    modifier = Modifier.padding(paddingValues)
                )
            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                        .testTag(AccessibilityIds.Residence.manageUsersList),
                    contentPadding = PaddingValues(OrganicSpacing.lg),
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.lg)
                ) {
                    // Share sections (primary owner only)
                    if (isPrimaryOwner) {
                        // Easy Share Section
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                accentColor = MaterialTheme.colorScheme.primaryContainer
                            ) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                                    ) {
                                        Icon(
                                            Icons.Default.Share,
                                            contentDescription = null, // decorative
                                            tint = MaterialTheme.colorScheme.onPrimaryContainer
                                        )
                                        Text(
                                            text = stringResource(Res.string.manage_users_easy_share),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.SemiBold,
                                            color = MaterialTheme.colorScheme.onPrimaryContainer
                                        )
                                    }

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

                                    OrganicPrimaryButton(
                                        text = stringResource(Res.string.manage_users_send_invite),
                                        onClick = onSharePackage,
                                        modifier = Modifier.fillMaxWidth(),
                                        icon = Icons.Default.Send
                                    )

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

                                    Text(
                                        text = stringResource(Res.string.manage_users_easy_share_desc),
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)
                                    )
                                }
                            }
                        }

                        // Divider with "or"
                        item {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                OrganicDivider(modifier = Modifier.weight(1f))
                                Text(
                                    text = stringResource(Res.string.manage_users_or),
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    modifier = Modifier.padding(horizontal = OrganicSpacing.lg)
                                )
                                OrganicDivider(modifier = Modifier.weight(1f))
                            }
                        }

                        // Share Code Section
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Column(
                                    modifier = Modifier.padding(OrganicSpacing.lg)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                                    ) {
                                        OrganicIconContainer(
                                            icon = Icons.Default.Key,
                                            size = 24.dp
                                        )
                                        Text(
                                            text = stringResource(Res.string.manage_users_share_code),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.SemiBold
                                        )
                                    }

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

                                    // Share code display
                                    OrganicCard(
                                        modifier = Modifier.fillMaxWidth(),
                                        accentColor = MaterialTheme.colorScheme.surface
                                    ) {
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(OrganicSpacing.lg),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            if (shareCode != null) {
                                                Text(
                                                    text = shareCode!!.code,
                                                    style = MaterialTheme.typography.headlineMedium.copy(
                                                        fontFamily = FontFamily.Monospace,
                                                        letterSpacing = 4.sp
                                                    ),
                                                    color = MaterialTheme.colorScheme.primary,
                                                    fontWeight = FontWeight.Bold
                                                )
                                                IconButton(
                                                    onClick = {
                                                        clipboardManager.setText(AnnotatedString(shareCode!!.code))
                                                        scope.launch {
                                                            snackbarHostState.showSnackbar("Code copied to clipboard")
                                                        }
                                                    }
                                                ) {
                                                    Icon(
                                                        Icons.Default.ContentCopy,
                                                        contentDescription = "Copy code",
                                                        tint = MaterialTheme.colorScheme.primary
                                                    )
                                                }
                                            } else {
                                                Text(
                                                    text = stringResource(Res.string.manage_users_no_code),
                                                    style = MaterialTheme.typography.bodyLarge,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                                )
                                            }
                                        }
                                    }

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

                                    OrganicPrimaryButton(
                                        text = if (shareCode != null) stringResource(Res.string.manage_users_generate_new)
                                               else stringResource(Res.string.manage_users_generate),
                                        onClick = {
                                            scope.launch {
                                                isGeneratingCode = true
                                                when (val result = APILayer.generateShareCode(residenceId)) {
                                                    is ApiResult.Success -> {
                                                        shareCode = result.data.shareCode
                                                    }
                                                    is ApiResult.Error -> {
                                                        error = result.message
                                                    }
                                                    else -> {}
                                                }
                                                isGeneratingCode = false
                                            }
                                        },
                                        modifier = Modifier.fillMaxWidth(),
                                        enabled = !isGeneratingCode,
                                        isLoading = isGeneratingCode,
                                        icon = Icons.Default.Refresh
                                    )

                                    if (shareCode != null) {
                                        Spacer(modifier = Modifier.height(OrganicSpacing.sm))
                                        Text(
                                            text = stringResource(Res.string.manage_users_code_desc),
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            }
                        }

                        item {
                            OrganicDivider()
                        }
                    }

                    // Users Header
                    item {
                        Text(
                            text = stringResource(Res.string.manage_users_users_count, users.size),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold
                        )
                    }

                    // Users List
                    items(users) { user ->
                        UserCard(
                            user = user,
                            isOwner = user.id == residenceOwnerId,
                            canRemove = isPrimaryOwner && user.id != residenceOwnerId,
                            onRemove = { showRemoveConfirmation = user }
                        )
                    }

                    // Bottom spacing
                    item {
                        Spacer(modifier = Modifier.height(OrganicSpacing.xl))
                    }
                }
            }
        }
    }

    // Remove User Confirmation Dialog
    showRemoveConfirmation?.let { user ->
        AlertDialog(
            onDismissRequest = { showRemoveConfirmation = null },
            title = { Text(stringResource(Res.string.manage_users_remove)) },
            text = { Text("Remove ${user.username} from this property?") },
            confirmButton = {
                TextButton(
                    onClick = {
                        scope.launch {
                            when (APILayer.removeUser(residenceId, user.id)) {
                                is ApiResult.Success -> {
                                    users = users.filter { it.id != user.id }
                                    onUserRemoved()
                                }
                                is ApiResult.Error -> {
                                    // Show error
                                }
                                else -> {}
                            }
                            showRemoveConfirmation = null
                        }
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(Res.string.manage_users_remove))
                }
            },
            dismissButton = {
                TextButton(onClick = { showRemoveConfirmation = null }) {
                    Text(stringResource(Res.string.common_cancel))
                }
            }
        )
    }
}

@Composable
private fun UserCard(
    user: ResidenceUser,
    isOwner: Boolean,
    canRemove: Boolean,
    onRemove: () -> Unit
) {
    OrganicCard(
        modifier = Modifier.fillMaxWidth()
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(OrganicSpacing.lg),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
            ) {
                // Avatar
                Surface(
                    shape = OrganicShapes.medium,
                    color = MaterialTheme.colorScheme.primaryContainer,
                    modifier = Modifier.size(48.dp)
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        Text(
                            text = user.username.take(2).uppercase(),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }

                Column {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                    ) {
                        Text(
                            text = user.username,
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.SemiBold
                        )
                        if (isOwner) {
                            Surface(
                                color = MaterialTheme.colorScheme.primaryContainer,
                                shape = OrganicShapes.extraSmall
                            ) {
                                Text(
                                    text = stringResource(Res.string.manage_users_owner_badge),
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                                    modifier = Modifier.padding(horizontal = OrganicSpacing.sm, vertical = 2.dp)
                                )
                            }
                        }
                    }

                    if (!user.email.isNullOrEmpty()) {
                        Text(
                            text = user.email,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }

                    val fullName = listOfNotNull(user.firstName, user.lastName)
                        .filter { it.isNotEmpty() }
                        .joinToString(" ")
                    if (fullName.isNotEmpty()) {
                        Text(
                            text = fullName,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }

            if (canRemove) {
                IconButton(
                    modifier = Modifier.testTag(AccessibilityIds.Residence.manageUsersRemoveButton),
                    onClick = onRemove
                ) {
                    Icon(
                        Icons.Default.Delete,
                        contentDescription = stringResource(Res.string.manage_users_remove),
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }
        }
    }
}
