package screens

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import at.mocode.clients.shared.presentation.store.AppStore
import at.mocode.clients.shared.presentation.state.AppState
import at.mocode.clients.pingfeature.PingViewModel
import at.mocode.ping.api.HealthResponse
import at.mocode.ping.api.PingResponse
import at.mocode.ping.api.EnhancedPingResponse

@Composable
fun DevelopmentScreen(appStore: AppStore) {
    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(
            "🚀 Meldestelle Development Mode",
            style = MaterialTheme.typography.headlineMedium
        )

        // Backend Connectivity Tests
        BackendTestSection()

        // Ping Service Test
        PingTestSection()

        // State Debugging
        StateDebugSection(appStore)
    }
}

@Composable
fun BackendTestSection() {
    Card(modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text("🌐 Backend Connectivity", style = MaterialTheme.typography.titleMedium)

            var testStatus by remember { mutableStateOf("Not tested") }
            var isLoading by remember { mutableStateOf(false) }

            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                Button(
                    onClick = {
                        // TODO: Test Gateway Connection
                        isLoading = true
                        testStatus = "Testing..."
                    },
                    enabled = !isLoading
                ) {
                    Text("Test Gateway")
                }

                Button(
                    onClick = {
                        // TODO: Test Ping Service Direct
                        isLoading = true
                        testStatus = "Testing direct connection..."
                    },
                    enabled = !isLoading
                ) {
                    Text("Test Ping Service")
                }
            }

            if (isLoading) {
                CircularProgressIndicator(modifier = Modifier.padding(8.dp))
            }

            Text("Status: $testStatus")
        }
    }
}

@Composable
fun PingTestSection() {
    val pingViewModel = remember { PingViewModel() }
    val uiState = pingViewModel.uiState

    Card(modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text("🏓 Ping Service Integration", style = MaterialTheme.typography.titleMedium)

            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                Button(
                    onClick = { pingViewModel.performHealthCheck() },
                    enabled = !uiState.isLoading
                ) {
                    Text("Health Check")
                }

                Button(
                    onClick = { pingViewModel.performSimplePing() },
                    enabled = !uiState.isLoading
                ) {
                    Text("Simple Ping")
                }

                Button(
                    onClick = { pingViewModel.performEnhancedPing(true) },
                    enabled = !uiState.isLoading
                ) {
                    Text("Test Circuit Breaker")
                }
            }

            if (uiState.isLoading) {
                LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp))
            }

            // Results Display
            uiState.healthResponse?.let { health ->
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer
                    )
                ) {
                    Column(modifier = Modifier.padding(8.dp)) {
                        Text("✅ Health Check Result:")
                        Text("Status: ${health.status}")
                        Text("Service: ${health.service}")
                        Text("Healthy: ${health.healthy}")
                        Text("Timestamp: ${health.timestamp}")
                    }
                }
            }

            uiState.simplePingResponse?.let { ping ->
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.secondaryContainer
                    )
                ) {
                    Column(modifier = Modifier.padding(8.dp)) {
                        Text("🏓 Simple Ping Result:")
                        Text("Status: ${ping.status}")
                        Text("Service: ${ping.service}")
                        Text("Timestamp: ${ping.timestamp}")
                    }
                }
            }

            uiState.enhancedPingResponse?.let { ping ->
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.tertiaryContainer
                    )
                ) {
                    Column(modifier = Modifier.padding(8.dp)) {
                        Text("⚡ Enhanced Ping Result:")
                        Text("Status: ${ping.status}")
                        Text("Circuit Breaker: ${ping.circuitBreakerState}")
                        Text("Response Time: ${ping.responseTime}ms")
                        Text("Service: ${ping.service}")
                    }
                }
            }

            uiState.errorMessage?.let { error ->
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer
                    )
                ) {
                    Text(
                        "❌ Error: $error",
                        color = MaterialTheme.colorScheme.onErrorContainer,
                        modifier = Modifier.padding(8.dp)
                    )
                }
            }
        }
    }
}

@Composable
fun StateDebugSection(appStore: AppStore) {
    val appState by appStore.state.collectAsState()

    Card(modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text("🔍 App State Debug", style = MaterialTheme.typography.titleMedium)

            Text("Auth State: ${if(appState.auth.isAuthenticated) "✅ Authenticated" else "❌ Not Authenticated"}")
            Text("Current Route: ${appState.navigation.currentRoute}")
            Text("Dark Mode: ${if(appState.ui.isDarkMode) "🌙 Enabled" else "☀️ Disabled"}")
            Text("Online: ${if(appState.network.isOnline) "🟢 Online" else "🔴 Offline"}")

            Button(
                onClick = {
                    appStore.dispatch(at.mocode.clients.shared.presentation.actions.AppAction.UI.ToggleDarkMode)
                }
            ) {
                Text("Toggle Dark Mode")
            }
        }
    }
}
