package dev.zxq5.chatapp.android

import android.Manifest
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ChatBubbleOutline
import androidx.compose.material.icons.outlined.PeopleOutline
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import dev.zxq5.chatapp.android.ChatApplication.AppState
import dev.zxq5.chatapp.android.core.service.MessageStreamService
import dev.zxq5.chatapp.android.data.repository.AuthState
import dev.zxq5.chatapp.android.feature.auth.AuthScreen
import dev.zxq5.chatapp.android.feature.auth.AuthViewModel
import dev.zxq5.chatapp.android.feature.chat.ChatScreen
import dev.zxq5.chatapp.android.feature.chat.ChatViewModel
import dev.zxq5.chatapp.android.feature.chat.Screen
import dev.zxq5.chatapp.android.feature.contacts.ContactsScreen
import dev.zxq5.chatapp.android.feature.settings.SettingsScreen
import dev.zxq5.chatapp.android.feature.settings.SettingsViewModel
import dev.zxq5.chatapp.android.ui.theme.ChatappTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        val app = application as ChatApplication
        val authRepository = app.authRepository
        val chatRepository = app.chatRepository
        val settingsRepository = app.settingsRepository

        enableEdgeToEdge()
        setContent {
            ChatappTheme {
                val authViewModel: AuthViewModel = viewModel(factory = ViewModelFactory(authRepository))
                val chatViewModel: ChatViewModel = viewModel(factory = ViewModelFactory(chatRepository))
                val settingsViewModel: SettingsViewModel = viewModel(factory = ViewModelFactory(settingsRepository))
                
                val authState by authViewModel.authState.collectAsState()
                val currentScreen by chatViewModel.currentScreen.collectAsState()
                val selectedChannelId by chatViewModel.channelId.collectAsState()

                // Permission request launcher
                val launcher = rememberLauncherForActivityResult(
                    contract = ActivityResultContracts.RequestPermission(),
                    onResult = { isGranted ->
                        if (isGranted && authState == AuthState.Authenticated) {
                            MessageStreamService.start(this@MainActivity)
                        }
                    }
                )

                LaunchedEffect(authState) {
                    when (authState) {
                        AuthState.Authenticated -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
                            }
                            MessageStreamService.start(this@MainActivity)
                            chatViewModel.loadAccessibleChannels()
                        }
                        AuthState.Unauthenticated -> MessageStreamService.stop(this@MainActivity)
                        AuthState.AwaitingTotp -> {}
                    }
                }

                LaunchedEffect(Unit) {
                    chatViewModel.onUnauthorized = {
                        authViewModel.logout()
                        chatViewModel.clearChat()
                    }
                }

                LaunchedEffect(Unit) {
                    intent.getIntExtra("channel_id", -1).takeIf { it != -1 }?.let {
                        chatViewModel.switchChannel(it.toLong())
                    }
                }

                if (authState == AuthState.Authenticated) {
                    Scaffold(
                        modifier = Modifier.fillMaxSize(),
                        bottomBar = {
                            // Only show bottom bar if we are NOT inside a specific chat channel
                            if (selectedChannelId == null) {
                                BottomDock(
                                    currentScreen = currentScreen,
                                    onNavigate = { chatViewModel.navigateTo(it) }
                                )
                            }
                        }
                    ) { innerPadding ->
                        Box(modifier = Modifier.padding(innerPadding)) {
                            when (currentScreen) {
                                Screen.CHAT -> ChatScreen(
                                    viewModel = chatViewModel,
                                    onNavigateToSettings = { chatViewModel.navigateTo(Screen.SETTINGS) },
                                    onLogout = { 
                                        authViewModel.logout()
                                        chatViewModel.clearChat()
                                    }
                                )
                                Screen.CONTACTS -> ContactsScreen()
                                Screen.SETTINGS -> SettingsScreen(
                                    viewModel = settingsViewModel,
                                    onLogout = {
                                        authViewModel.logout()
                                        chatViewModel.clearChat()
                                    }
                                )
                            }
                        }
                    }
                } else {
                    AuthScreen(viewModel = authViewModel)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        AppState.isInForeground = true
    }

    override fun onPause() {
        super.onPause()
        AppState.isInForeground = false
    }

    override fun onNewIntent(intent: android.content.Intent) {
        super.onNewIntent(intent)
        intent.getIntExtra("channel_id", -1).takeIf { it != -1 }?.let { channelId ->
            MessageStreamService.instance?.activeChannelId = channelId.toLong()
        }
    }
}

@Composable
fun BottomDock(currentScreen: Screen, onNavigate: (Screen) -> Unit) {
    NavigationBar(
        containerColor = MaterialTheme.colorScheme.background,
        tonalElevation = 0.dp,
        modifier = Modifier
            .height(80.dp)
            .border(
                0.5.dp, 
                MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f), 
                RoundedCornerShape(topStart = 0.dp, topEnd = 0.dp)
            )
    ) {
        NavigationBarItem(
            selected = currentScreen == Screen.CHAT,
            onClick = { onNavigate(Screen.CHAT) },
            icon = { Icon(Icons.Outlined.ChatBubbleOutline, contentDescription = "Chat") },
            label = { Text("chat", style = MaterialTheme.typography.labelSmall) },
            colors = NavigationBarItemDefaults.colors(
                selectedIconColor = MaterialTheme.colorScheme.primary,
                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                indicatorColor = Color.Transparent
            )
        )
        NavigationBarItem(
            selected = currentScreen == Screen.CONTACTS,
            onClick = { onNavigate(Screen.CONTACTS) },
            icon = { Icon(Icons.Outlined.PeopleOutline, contentDescription = "Contacts") },
            label = { Text("contacts", style = MaterialTheme.typography.labelSmall) },
            colors = NavigationBarItemDefaults.colors(
                selectedIconColor = MaterialTheme.colorScheme.primary,
                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                indicatorColor = Color.Transparent
            )
        )
        NavigationBarItem(
            selected = currentScreen == Screen.SETTINGS,
            onClick = { onNavigate(Screen.SETTINGS) },
            icon = { Icon(Icons.Outlined.Settings, contentDescription = "Settings") },
            label = { Text("settings", style = MaterialTheme.typography.labelSmall) },
            colors = NavigationBarItemDefaults.colors(
                selectedIconColor = MaterialTheme.colorScheme.primary,
                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                indicatorColor = Color.Transparent
            )
        )
    }
}
