package com.tt.honeyDue.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.network.APILayer
import kotlinx.coroutines.launch

@Composable
fun JoinResidenceDialog(
    onDismiss: () -> Unit,
    onJoined: () -> Unit = {}
) {
    var shareCode by remember { mutableStateOf(TextFieldValue("")) }
    var isJoining by remember { mutableStateOf(false) }
    var error by remember { mutableStateOf<String?>(null) }

    val scope = rememberCoroutineScope()

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text("Join Residence")
                IconButton(onClick = onDismiss) {
                    Icon(Icons.Default.Close, "Close")
                }
            }
        },
        text = {
            Column(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = "Enter the 6-character share code to join a residence",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                OutlinedTextField(
                    value = shareCode,
                    onValueChange = {
                        if (it.text.length <= 6) {
                            shareCode = it.copy(text = it.text.uppercase())
                            error = null
                        }
                    },
                    label = { Text("Share Code") },
                    placeholder = { Text("ABC123") },
                    singleLine = true,
                    enabled = !isJoining,
                    isError = error != null,
                    supportingText = {
                        if (error != null) {
                            Text(
                                text = error ?: "",
                                color = MaterialTheme.colorScheme.error
                            )
                        }
                    },
                    modifier = Modifier.fillMaxWidth()
                )

                if (isJoining) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    if (shareCode.text.length == 6) {
                        scope.launch {
                            isJoining = true
                            error = null
                            when (val result = APILayer.joinWithCode(shareCode.text)) {
                                is ApiResult.Success -> {
                                    isJoining = false
                                    onJoined()
                                    onDismiss()
                                }
                                is ApiResult.Error -> {
                                    error = result.message
                                    isJoining = false
                                }
                                else -> {
                                    isJoining = false
                                }
                            }
                        }
                    } else {
                        error = "Share code must be 6 characters"
                    }
                },
                enabled = !isJoining && shareCode.text.length == 6
            ) {
                Text("Join")
            }
        },
        dismissButton = {
            TextButton(
                onClick = onDismiss,
                enabled = !isJoining
            ) {
                Text("Cancel")
            }
        }
    )
}
