package de.oaa.xxx.app

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.*
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import de.oaa.xxx.app.data.model.User
import de.oaa.xxx.app.ui.navigation.Routes
import de.oaa.xxx.app.ui.screens.aufgaben.AufgabenScreen
import de.oaa.xxx.app.ui.screens.auth.LoginScreen
import de.oaa.xxx.app.ui.screens.auth.RegisterScreen
import de.oaa.xxx.app.ui.screens.feed.FeedScreen
import de.oaa.xxx.app.ui.screens.gruppen.GruppenScreen
import de.oaa.xxx.app.ui.screens.home.HomeScreen
import de.oaa.xxx.app.ui.screens.profile.ProfileScreen
import de.oaa.xxx.app.ui.screens.session.SessionInGameScreen
import de.oaa.xxx.app.ui.screens.session.SessionSetupScreen
import de.oaa.xxx.app.ui.screens.social.ConversationScreen
import de.oaa.xxx.app.ui.screens.social.FriendsScreen
import de.oaa.xxx.app.ui.screens.social.MessagesScreen
import de.oaa.xxx.app.ui.theme.XxxGameTheme
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
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.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import de.oaa.xxx.app.data.model.AufgabenGruppenRef
import de.oaa.xxx.app.ui.viewmodel.AufgabenViewModel
import de.oaa.xxx.app.ui.viewmodel.AuthState
import de.oaa.xxx.app.ui.viewmodel.AuthViewModel
import de.oaa.xxx.app.ui.viewmodel.FeedViewModel
import de.oaa.xxx.app.ui.viewmodel.SessionViewModel
import de.oaa.xxx.app.ui.viewmodel.SocialViewModel
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            XxxGameTheme {
                XxxApp()
            }
        }
    }
}

@Composable
fun XxxApp() {
    val navController = rememberNavController()
    val authViewModel: AuthViewModel = viewModel()
    val sessionViewModel: SessionViewModel = viewModel()
    val aufgabenViewModel: AufgabenViewModel = viewModel()
    val socialViewModel: SocialViewModel = viewModel()
    val feedViewModel: FeedViewModel = viewModel()

    val authState by authViewModel.state.collectAsState()
    var currentUser by remember { mutableStateOf<User?>(null) }
    var conversationPartnerName by remember { mutableStateOf("") }

    LaunchedEffect(authState) {
        when (authState) {
            is AuthState.LoggedIn -> {
                currentUser = (authState as AuthState.LoggedIn).user
                navController.navigate(Routes.HOME) {
                    popUpTo(Routes.LOGIN) { inclusive = true }
                }
            }
            is AuthState.LoggedOut -> {
                navController.navigate(Routes.LOGIN) {
                    popUpTo(0) { inclusive = true }
                }
            }
            else -> {}
        }
    }

    NavHost(navController = navController, startDestination = Routes.LOGIN) {

        composable(Routes.LOGIN) {
            LoginScreen(
                viewModel = authViewModel,
                onLoginSuccess = {},
                onNavigateToRegister = { navController.navigate(Routes.REGISTER) }
            )
        }

        composable(Routes.REGISTER) {
            RegisterScreen(
                viewModel = authViewModel,
                onNavigateBack = { navController.popBackStack() }
            )
        }

        composable(Routes.HOME) {
            currentUser?.let { user ->
                HomeScreen(
                    user = user,
                    onNavigate = { route -> navController.navigate(route) },
                    onLogout = { authViewModel.logout() }
                )
            }
        }

        composable(Routes.AUFGABEN) {
            AufgabenScreen(
                viewModel = aufgabenViewModel,
                onNavigateBack = { navController.popBackStack() },
                onGruppeClick = { gruppenId ->
                    navController.navigate("aufgaben/$gruppenId")
                }
            )
        }

        composable(
            "aufgaben/{gruppenId}",
            arguments = listOf(navArgument("gruppenId") { type = NavType.StringType })
        ) { backStack ->
            val gruppenId = backStack.arguments?.getString("gruppenId") ?: return@composable
            LaunchedEffect(gruppenId) { aufgabenViewModel.loadGruppe(gruppenId) }
            // Group detail - reuse AufgabenScreen for now
            AufgabenScreen(
                viewModel = aufgabenViewModel,
                onNavigateBack = { navController.popBackStack() },
                onGruppeClick = {}
            )
        }

        composable(Routes.SESSION_SETUP) {
            currentUser?.let { user ->
                SessionSetupScreen(
                    viewModel = sessionViewModel,
                    currentUser = user,
                    onNavigateBack = { navController.popBackStack() },
                    onSessionCreated = { sessionId ->
                        navController.navigate("session/players/$sessionId")
                    }
                )
            }
        }

        composable(
            "session/players/{sessionId}",
            arguments = listOf(navArgument("sessionId") { type = NavType.StringType })
        ) { backStack ->
            val sessionId = backStack.arguments?.getString("sessionId") ?: return@composable
            // Navigate directly to task selection
            navController.navigate("session/tasks/$sessionId") {
                popUpTo("session/players/$sessionId") { inclusive = true }
            }
        }

        composable(
            "session/tasks/{sessionId}",
            arguments = listOf(navArgument("sessionId") { type = NavType.StringType })
        ) { backStack ->
            val sessionId = backStack.arguments?.getString("sessionId") ?: return@composable
            // Show task group selection for session
            SessionTaskSelectionScreen(
                sessionId = sessionId,
                aufgabenViewModel = aufgabenViewModel,
                sessionViewModel = sessionViewModel,
                onNavigateBack = { navController.popBackStack() },
                onReady = { navController.navigate("session/ingame/$sessionId") }
            )
        }

        composable(
            Routes.SESSION_INGAME,
            arguments = listOf(navArgument("sessionId") { type = NavType.StringType })
        ) { backStack ->
            val sessionId = backStack.arguments?.getString("sessionId") ?: return@composable
            SessionInGameScreen(
                viewModel = sessionViewModel,
                sessionId = sessionId,
                onSessionEnd = {
                    navController.navigate(Routes.HOME) {
                        popUpTo(Routes.HOME) { inclusive = true }
                    }
                },
                onNavigateBack = { navController.popBackStack() }
            )
        }

        composable(Routes.PROFILE) {
            currentUser?.let { user ->
                ProfileScreen(
                    currentUser = user,
                    onNavigateBack = { navController.popBackStack() },
                    onUserUpdated = { updatedUser -> currentUser = updatedUser }
                )
            }
        }

        composable(Routes.FRIENDS) {
            FriendsScreen(
                viewModel = socialViewModel,
                currentUserId = currentUser?.userId ?: "",
                onNavigateBack = { navController.popBackStack() },
                onOpenMessages = { partnerId ->
                    navController.navigate("messages/$partnerId")
                }
            )
        }

        composable(Routes.MESSAGES) {
            MessagesScreen(
                viewModel = socialViewModel,
                onNavigateBack = { navController.popBackStack() },
                onOpenConversation = { partnerId ->
                    navController.navigate("messages/$partnerId")
                }
            )
        }

        composable(
            "messages/{partnerId}",
            arguments = listOf(navArgument("partnerId") { type = NavType.StringType })
        ) { backStack ->
            val partnerId = backStack.arguments?.getString("partnerId") ?: return@composable
            ConversationScreen(
                viewModel = socialViewModel,
                partnerId = partnerId,
                currentUserId = currentUser?.userId ?: "",
                partnerName = conversationPartnerName.ifBlank { "Konversation" },
                onNavigateBack = { navController.popBackStack() }
            )
        }

        composable(Routes.GRUPPEN) {
            GruppenScreen(
                currentUserId = currentUser?.userId ?: "",
                onNavigateBack = { navController.popBackStack() }
            )
        }

        composable(Routes.FEED) {
            FeedScreen(
                viewModel = feedViewModel,
                onNavigateBack = { navController.popBackStack() }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionTaskSelectionScreen(
    sessionId: String,
    aufgabenViewModel: AufgabenViewModel,
    sessionViewModel: SessionViewModel,
    onNavigateBack: () -> Unit,
    onReady: () -> Unit
) {
    val userGruppen by aufgabenViewModel.userGruppen.collectAsState()
    val subscriptions by aufgabenViewModel.subscriptions.collectAsState()
    val isLoading by sessionViewModel.isLoading.collectAsState()
    val selectedGruppenIds = remember { mutableStateListOf<String>() }

    LaunchedEffect(Unit) {
        aufgabenViewModel.loadUserGruppen()
        aufgabenViewModel.loadSubscriptions()
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Aufgaben auswählen") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Zurück")
                    }
                }
            )
        }
    ) { padding ->
        val allGruppen = (userGruppen + subscriptions).distinctBy { it.gruppenId }
        LazyColumn(
            modifier = Modifier.fillMaxSize().padding(padding).padding(horizontal = 16.dp),
            verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 16.dp)
        ) {
            items(allGruppen) { gruppe ->
                val isSelected = gruppe.gruppenId in selectedGruppenIds
                Card(
                    onClick = {
                        if (isSelected) selectedGruppenIds.remove(gruppe.gruppenId)
                        else gruppe.gruppenId?.let { selectedGruppenIds.add(it) }
                    },
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
                        else MaterialTheme.colorScheme.surface
                    )
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Checkbox(
                            checked = isSelected,
                            onCheckedChange = {
                                if (isSelected) selectedGruppenIds.remove(gruppe.gruppenId)
                                else gruppe.gruppenId?.let { id -> selectedGruppenIds.add(id) }
                            }
                        )
                        Text(gruppe.name ?: "(Unbekannt)", modifier = Modifier.weight(1f))
                    }
                }
            }

            item {
                Spacer(modifier = Modifier.height(8.dp))
                Button(
                    onClick = {
                        if (selectedGruppenIds.isNotEmpty()) {
                            val refs = selectedGruppenIds.map { AufgabenGruppenRef(gruppenId = it) }
                            sessionViewModel.setAufgaben(sessionId, refs) { onReady() }
                        }
                    },
                    modifier = Modifier.fillMaxWidth().height(52.dp),
                    enabled = selectedGruppenIds.isNotEmpty() && !isLoading
                ) {
                    if (isLoading) CircularProgressIndicator(modifier = Modifier.size(24.dp))
                    else Text("Session starten", fontSize = 16.sp)
                }
            }
        }
    }
}
