package com.tt.honeyDue.ui.components

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.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.PersonAdd
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Share
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.text.AnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
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.ui.theme.AppSpacing
import kotlinx.coroutines.launch

@Composable
fun ManageUsersDialog(
    residenceId: Int,
    residenceName: String,
    isPrimaryOwner: Boolean,
    residenceOwnerId: Int,
    onDismiss: () -> Unit,
    onUserRemoved: () -> Unit = {},
    onSharePackage: () -> Unit = {}
) {
    var users by remember { mutableStateOf<List<ResidenceUser>>(emptyList()) }
    val ownerId = residenceOwnerId
    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) }

    val scope = rememberCoroutineScope()
    val clipboardManager = LocalClipboardManager.current

    // Load users
    LaunchedEffect(residenceId) {
        // Clear share code on open so it's always blank
        shareCode = null

        when (val result = APILayer.getResidenceUsers(residenceId)) {
            is ApiResult.Success -> {
                users = result.data
                isLoading = false
            }
            is ApiResult.Error -> {
                error = result.message
                isLoading = false
            }
            else -> {}
        }

        // Don't auto-load share code - user must generate it explicitly
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        Icons.Default.PersonAdd,
                        contentDescription = null, // decorative
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(28.dp)
                    )
                    Spacer(modifier = Modifier.width(AppSpacing.sm))
                    Text("Invite Others")
                }
                IconButton(onClick = onDismiss) {
                    Icon(Icons.Default.Close, "Close")
                }
            }
        },
        text = {
            Column(modifier = Modifier.fillMaxWidth()) {
                if (isLoading) {
                    Box(
                        modifier = Modifier.fillMaxWidth().padding(32.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                } else if (error != null) {
                    Text(
                        text = error ?: "Unknown error",
                        color = MaterialTheme.colorScheme.error,
                        modifier = Modifier.padding(AppSpacing.lg)
                    )
                } else {
                    // Share sections (primary owner only)
                    if (isPrimaryOwner) {
                        // Easy Share section (on top - recommended)
                        Card(
                            modifier = Modifier.fillMaxWidth().padding(bottom = AppSpacing.sm),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            )
                        ) {
                            Column(modifier = Modifier.padding(AppSpacing.lg)) {
                                Text(
                                    text = "Easy Share",
                                    style = MaterialTheme.typography.titleSmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                                Spacer(modifier = Modifier.height(AppSpacing.sm))

                                Button(
                                    onClick = { onSharePackage() },
                                    modifier = Modifier.fillMaxWidth()
                                ) {
                                    Icon(Icons.Default.Share, "Share", modifier = Modifier.size(18.dp))
                                    Spacer(modifier = Modifier.width(AppSpacing.sm))
                                    Text("Send Invite Link")
                                }

                                Text(
                                    text = "Send a .honeydue file via Messages, Email, or share. They just tap to join.",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    modifier = Modifier.padding(top = AppSpacing.sm)
                                )
                            }
                        }

                        // Divider with "or"
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(vertical = AppSpacing.sm),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            HorizontalDivider(modifier = Modifier.weight(1f))
                            Text(
                                text = "or",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                modifier = Modifier.padding(horizontal = AppSpacing.lg)
                            )
                            HorizontalDivider(modifier = Modifier.weight(1f))
                        }

                        // Share Code section
                        Card(
                            modifier = Modifier.fillMaxWidth().padding(bottom = AppSpacing.lg),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            )
                        ) {
                            Column(modifier = Modifier.padding(AppSpacing.lg)) {
                                Text(
                                    text = "Share Code",
                                    style = MaterialTheme.typography.titleSmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                                Spacer(modifier = Modifier.height(AppSpacing.sm))

                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    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
                                        )
                                        IconButton(
                                            onClick = {
                                                clipboardManager.setText(AnnotatedString(shareCode!!.code))
                                            }
                                        ) {
                                            Icon(
                                                Icons.Default.ContentCopy,
                                                contentDescription = "Copy code",
                                                tint = MaterialTheme.colorScheme.primary
                                            )
                                        }
                                    } else {
                                        Text(
                                            text = "No active code",
                                            style = MaterialTheme.typography.bodyMedium.copy(
                                                fontStyle = FontStyle.Italic
                                            ),
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }

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

                                Button(
                                    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
                                        }
                                    },
                                    enabled = !isGeneratingCode,
                                    modifier = Modifier.fillMaxWidth()
                                ) {
                                    if (isGeneratingCode) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(18.dp),
                                            color = MaterialTheme.colorScheme.onPrimary,
                                            strokeWidth = 2.dp
                                        )
                                    } else {
                                        Icon(Icons.Default.Refresh, "Generate", modifier = Modifier.size(18.dp))
                                    }
                                    Spacer(modifier = Modifier.width(AppSpacing.sm))
                                    Text(if (shareCode != null) "Generate New Code" else "Generate Code")
                                }

                                if (shareCode != null) {
                                    Text(
                                        text = "Share this 6-character code. They can enter it in the app to join.",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier.padding(top = AppSpacing.sm)
                                    )
                                }
                            }
                        }
                    }

                    // Users list
                    Text(
                        text = "Users (${users.size})",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = AppSpacing.sm)
                    )

                    LazyColumn(
                        modifier = Modifier.fillMaxWidth().height(200.dp)
                    ) {
                        items(users) { user ->
                            UserListItem(
                                user = user,
                                isOwner = user.id == ownerId,
                                isPrimaryOwner = isPrimaryOwner,
                                onRemove = {
                                    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 -> {}
                                        }
                                    }
                                }
                            )
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Close")
            }
        }
    )
}

@Composable
private fun UserListItem(
    user: ResidenceUser,
    isOwner: Boolean,
    isPrimaryOwner: Boolean,
    onRemove: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth().padding(vertical = AppSpacing.xs)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(AppSpacing.md),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = user.username,
                        style = MaterialTheme.typography.bodyLarge
                    )
                    if (isOwner) {
                        Spacer(modifier = Modifier.width(AppSpacing.sm))
                        Surface(
                            color = MaterialTheme.colorScheme.primaryContainer,
                            shape = MaterialTheme.shapes.small
                        ) {
                            Text(
                                text = "Owner",
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onPrimaryContainer,
                                modifier = Modifier.padding(horizontal = 6.dp, 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 (isPrimaryOwner && !isOwner) {
                IconButton(onClick = onRemove) {
                    Icon(
                        Icons.Default.Delete,
                        contentDescription = "Remove user",
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }
        }
    }
}
