package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import com.tt.honeyDue.navigation.*
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.models.Residence
import com.tt.honeyDue.models.TaskDetail
import com.tt.honeyDue.platform.PlatformUpgradeScreen
import com.tt.honeyDue.storage.TokenStorage
import com.tt.honeyDue.ui.screens.theme.ThemeSelectionScreen
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import kotlinx.serialization.json.Json
import org.jetbrains.compose.resources.stringResource

@Composable
fun MainScreen(
    onLogout: () -> Unit,
    onResidenceClick: (Int) -> Unit,
    onAddResidence: () -> Unit,
    onNavigateToEditResidence: (Residence) -> Unit,
    onNavigateToEditTask: (com.tt.honeyDue.models.TaskDetail) -> Unit,
    onAddTask: () -> Unit,
    navigateToTaskId: Int? = null,
    onClearNavigateToTask: () -> Unit = {}
) {
    var selectedTab by remember { mutableStateOf(0) }
    val navController = rememberNavController()

    // When navigateToTaskId is set, switch to tasks tab
    LaunchedEffect(navigateToTaskId) {
        if (navigateToTaskId != null) {
            selectedTab = 1
            navController.navigate(MainTabTasksRoute) {
                popUpTo(MainTabResidencesRoute) { inclusive = false }
            }
        }
    }

    WarmGradientBackground {
        Scaffold(
            containerColor = androidx.compose.ui.graphics.Color.Transparent,
            bottomBar = {
                NavigationBar(
                    containerColor = MaterialTheme.colorScheme.surfaceContainer,
                    tonalElevation = 3.dp
                ) {
                        NavigationBarItem(
                            icon = { Icon(Icons.Default.Home, contentDescription = stringResource(Res.string.properties_title)) },
                            label = { Text(stringResource(Res.string.properties_title)) },
                            selected = selectedTab == 0,
                            onClick = {
                                selectedTab = 0
                                navController.navigate(MainTabResidencesRoute) {
                                    popUpTo(MainTabResidencesRoute) { inclusive = true }
                                }
                            },
                            colors = NavigationBarItemDefaults.colors(
                                selectedIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                selectedTextColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                indicatorColor = MaterialTheme.colorScheme.secondaryContainer,
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        )
                        NavigationBarItem(
                            icon = { Icon(Icons.Default.CheckCircle, contentDescription = stringResource(Res.string.tasks_title)) },
                            label = { Text(stringResource(Res.string.tasks_title)) },
                            selected = selectedTab == 1,
                            onClick = {
                                selectedTab = 1
                                navController.navigate(MainTabTasksRoute) {
                                    popUpTo(MainTabResidencesRoute) { inclusive = false }
                                }
                            },
                            colors = NavigationBarItemDefaults.colors(
                                selectedIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                selectedTextColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                indicatorColor = MaterialTheme.colorScheme.secondaryContainer,
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        )
                        NavigationBarItem(
                            icon = { Icon(Icons.Default.Build, contentDescription = stringResource(Res.string.contractors_title)) },
                            label = { Text(stringResource(Res.string.contractors_title)) },
                            selected = selectedTab == 2,
                            onClick = {
                                selectedTab = 2
                                navController.navigate(MainTabContractorsRoute) {
                                    popUpTo(MainTabResidencesRoute) { inclusive = false }
                                }
                            },
                            colors = NavigationBarItemDefaults.colors(
                                selectedIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                selectedTextColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                indicatorColor = MaterialTheme.colorScheme.secondaryContainer,
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        )
                        NavigationBarItem(
                            icon = { Icon(Icons.Default.Description, contentDescription = stringResource(Res.string.documents_title)) },
                            label = { Text(stringResource(Res.string.documents_title)) },
                            selected = selectedTab == 3,
                            onClick = {
                                selectedTab = 3
                                navController.navigate(MainTabDocumentsRoute) {
                                    popUpTo(MainTabResidencesRoute) { inclusive = false }
                                }
                            },
                            colors = NavigationBarItemDefaults.colors(
                                selectedIconColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                selectedTextColor = MaterialTheme.colorScheme.onSecondaryContainer,
                                indicatorColor = MaterialTheme.colorScheme.secondaryContainer,
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        )
                }
            }
        ) { paddingValues ->
            NavHost(
                navController = navController,
                startDestination = MainTabResidencesRoute,
                modifier = Modifier.fillMaxSize()
            ) {
                composable<MainTabResidencesRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        ResidencesScreen(
                            onResidenceClick = onResidenceClick,
                            onAddResidence = onAddResidence,
                            onJoinResidence = {
                                navController.navigate(JoinResidenceRoute)
                            },
                            onLogout = onLogout,
                            onNavigateToProfile = {
                                // Don't change selectedTab since Profile isn't in the bottom nav
                                navController.navigate(MainTabProfileRoute)
                            }
                        )
                    }
                }

                composable<JoinResidenceRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        com.tt.honeyDue.ui.screens.residence.JoinResidenceScreen(
                            onNavigateBack = { navController.navigateUp() },
                            onJoined = { residenceId ->
                                // Pop the join screen and hand off to the
                                // parent nav graph (ResidenceDetailRoute lives
                                // above MainScreen in App.kt).
                                navController.popBackStack()
                                onResidenceClick(residenceId)
                            },
                        )
                    }
                }

                composable<MainTabTasksRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        AllTasksScreen(
                            onNavigateToEditTask = onNavigateToEditTask,
                            onAddTask = onAddTask,
                            bottomNavBarPadding = paddingValues.calculateBottomPadding(),
                            navigateToTaskId = navigateToTaskId,
                            onClearNavigateToTask = onClearNavigateToTask,
                            onNavigateToCompleteTask = { task, residenceName ->
                                navController.navigate(
                                    CompleteTaskRoute(
                                        taskId = task.id,
                                        taskTitle = task.title,
                                        residenceName = residenceName
                                    )
                                )
                            }
                        )
                    }
                }

                composable<MainTabContractorsRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        ContractorsScreen(
                            onNavigateBack = {
                                selectedTab = 0
                                navController.navigate(MainTabResidencesRoute)
                            },
                            onNavigateToContractorDetail = { contractorId ->
                                navController.navigate(ContractorDetailRoute(contractorId))
                            }
                        )
                    }
                }

                composable<ContractorDetailRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<ContractorDetailRoute>()
                    Box(modifier = Modifier.fillMaxSize()) {
                        ContractorDetailScreen(
                            contractorId = route.contractorId,
                            onNavigateBack = {
                                navController.popBackStack()
                            }
                        )
                    }
                }

                composable<MainTabDocumentsRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        DocumentsScreen(
                            onNavigateBack = {
                                selectedTab = 0
                                navController.navigate(MainTabResidencesRoute)
                            },
                            residenceId = null,
                            onNavigateToAddDocument = { residenceId, documentType ->
                                navController.navigate(
                                    AddDocumentRoute(
                                        residenceId = residenceId,
                                        initialDocumentType = documentType
                                    )
                                )
                            },
                            onNavigateToDocumentDetail = { documentId ->
                                navController.navigate(DocumentDetailRoute(documentId))
                            }
                        )
                    }
                }

                composable<AddDocumentRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<AddDocumentRoute>()
                    AddDocumentScreen(
                        residenceId = route.residenceId,
                        initialDocumentType = route.initialDocumentType,
                        onNavigateBack = { navController.navigateUp() },
                        onDocumentCreated = {
                            navController.popBackStack()
                        }
                    )
                }

                composable<DocumentDetailRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<DocumentDetailRoute>()
                    DocumentDetailScreen(
                        documentId = route.documentId,
                        onNavigateBack = { navController.navigateUp() },
                        onNavigateToEdit = { documentId ->
                            navController.navigate(EditDocumentRoute(documentId))
                        }
                    )
                }

                composable<EditDocumentRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<EditDocumentRoute>()
                    EditDocumentScreen(
                        documentId = route.documentId,
                        onNavigateBack = { navController.navigateUp() }
                    )
                }

                composable<MainTabProfileRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        ProfileScreen(
                            onNavigateBack = {
                                selectedTab = 0
                                navController.navigate(MainTabResidencesRoute)
                            },
                            onLogout = onLogout,
                            onNavigateToNotificationPreferences = {
                                navController.navigate(NotificationPreferencesRoute)
                            },
                            onNavigateToThemeSelection = {
                                navController.navigate(ThemeSelectionRoute)
                            },
                            onNavigateToUpgrade = {
                                navController.navigate(UpgradeRoute)
                            }
                        )
                    }
                }

                composable<NotificationPreferencesRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        NotificationPreferencesScreen(
                            onNavigateBack = {
                                navController.popBackStack()
                            }
                        )
                    }
                }

                composable<ThemeSelectionRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        ThemeSelectionScreen(
                            onNavigateBack = {
                                navController.popBackStack()
                            }
                        )
                    }
                }

                composable<CompleteTaskRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<CompleteTaskRoute>()
                    Box(modifier = Modifier.fillMaxSize()) {
                        CompleteTaskScreen(
                            taskId = route.taskId,
                            taskTitle = route.taskTitle,
                            residenceName = route.residenceName,
                            onNavigateBack = {
                                navController.popBackStack()
                            },
                            onComplete = { request, images ->
                                // Navigation back happens in the screen after successful completion
                                navController.popBackStack()
                            }
                        )
                    }
                }

                composable<ManageUsersRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<ManageUsersRoute>()
                    Box(modifier = Modifier.fillMaxSize()) {
                        ManageUsersScreen(
                            residenceId = route.residenceId,
                            residenceName = route.residenceName,
                            isPrimaryOwner = route.isPrimaryOwner,
                            residenceOwnerId = route.residenceOwnerId,
                            onNavigateBack = {
                                navController.popBackStack()
                            },
                            onUserRemoved = {
                                // Could trigger a refresh if needed
                            }
                        )
                    }
                }

                composable<UpgradeRoute> {
                    Box(modifier = Modifier.fillMaxSize()) {
                        PlatformUpgradeScreen(
                            onNavigateBack = {
                                navController.popBackStack()
                            },
                            onSubscriptionChanged = {
                                // Subscription state updated via DataManager
                            }
                        )
                    }
                }
            }
        }
    }
}
