package de.oaa.xxx.app.ui.screens.session

import androidx.compose.animation.AnimatedContent
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.ArrowBack
import androidx.compose.material.icons.filled.NavigateNext
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import de.oaa.xxx.app.data.model.AufgabeAnzeige
import de.oaa.xxx.app.data.model.Session
import de.oaa.xxx.app.ui.viewmodel.SessionViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionInGameScreen(
    viewModel: SessionViewModel,
    sessionId: String,
    onSessionEnd: () -> Unit,
    onNavigateBack: () -> Unit
) {
    val currentAufgabe by viewModel.currentAufgabe.collectAsState()
    val finisherList by viewModel.finisherList.collectAsState()
    val session by viewModel.session.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val error by viewModel.error.collectAsState()
    var showEndDialog by remember { mutableStateOf(false) }
    var isFinished by remember { mutableStateOf(false) }

    LaunchedEffect(sessionId) {
        viewModel.getNextAufgabe(sessionId)
    }

    LaunchedEffect(finisherList) {
        if (finisherList.isNotEmpty()) isFinished = true
    }

    if (showEndDialog) {
        AlertDialog(
            onDismissRequest = { showEndDialog = false },
            title = { Text("Session beenden?") },
            text = { Text("Soll die aktuelle Session wirklich beendet werden?") },
            confirmButton = {
                TextButton(onClick = {
                    session?.let { viewModel.deleteSession(it) { onSessionEnd() } }
                    showEndDialog = false
                }) { Text("Beenden", color = MaterialTheme.colorScheme.error) }
            },
            dismissButton = {
                TextButton(onClick = { showEndDialog = false }) { Text("Abbrechen") }
            }
        )
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text("Level ${currentAufgabe?.level ?: session?.level ?: 1}")
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Zurück")
                    }
                },
                actions = {
                    IconButton(onClick = { showEndDialog = true }) {
                        Icon(Icons.Default.Stop, contentDescription = "Session beenden", tint = MaterialTheme.colorScheme.error)
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            if (isLoading) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator()
                }
            } else if (isFinished) {
                FinisherScreen(finisherList = finisherList, onEnd = {
                    session?.let { viewModel.deleteSession(it) { onSessionEnd() } }
                })
            } else {
                AnimatedContent(targetState = currentAufgabe, label = "aufgabe") { aufgabe ->
                    if (aufgabe != null) {
                        AufgabeDisplay(
                            aufgabe = aufgabe,
                            onNext = { viewModel.getNextAufgabe(sessionId) }
                        )
                    } else {
                        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Text("Warte auf nächste Aufgabe...", color = MaterialTheme.colorScheme.onBackground)
                                Spacer(modifier = Modifier.height(16.dp))
                                Button(onClick = { viewModel.getNextAufgabe(sessionId) }) {
                                    Text("Nächste Aufgabe")
                                }
                            }
                        }
                    }
                }
            }

            error?.let {
                Text(text = it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(top = 16.dp))
            }
        }
    }
}

@Composable
fun AufgabeDisplay(aufgabe: AufgabeAnzeige, onNext: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        aufgabe.nameAktiverMitspieler?.let {
            Text(
                text = it,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
        }

        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
        ) {
            Text(
                text = aufgabe.aufgabeText ?: "",
                modifier = Modifier.padding(24.dp),
                fontSize = 18.sp,
                textAlign = TextAlign.Center,
                lineHeight = 28.sp
            )
        }

        aufgabe.timer?.let { timer ->
            if (timer > 0) {
                Text(
                    text = "⏱ ${timer / 60}:${String.format("%02d", timer % 60)} min",
                    fontSize = 16.sp,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }

        Spacer(modifier = Modifier.height(24.dp))

        Button(
            onClick = onNext,
            modifier = Modifier.fillMaxWidth().height(52.dp)
        ) {
            Icon(Icons.Default.NavigateNext, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            Text("Nächste Aufgabe", fontSize = 16.sp)
        }
    }
}

@Composable
fun FinisherScreen(finisherList: List<AufgabeAnzeige>, onEnd: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Session abgeschlossen!",
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary,
            textAlign = TextAlign.Center
        )

        Spacer(modifier = Modifier.height(16.dp))

        Text("Finisher-Aufgaben:", fontSize = 16.sp, fontWeight = FontWeight.Medium)

        Spacer(modifier = Modifier.height(8.dp))

        LazyColumn(
            modifier = Modifier.weight(1f),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(finisherList) { finisher ->
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        finisher.nameAktiverMitspieler?.let {
                            Text(text = it, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
                        }
                        Text(text = finisher.aufgabeText ?: "", fontSize = 15.sp)
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        Button(onClick = onEnd, modifier = Modifier.fillMaxWidth().height(52.dp)) {
            Text("Session beenden", fontSize = 16.sp)
        }
    }
}
