package com.radiola

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
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 androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.lifecycle.lifecycleScope
import com.radiola.data.local.TokenDataStore
import com.radiola.ui.auth.AuthScreen
import com.radiola.ui.charts.ChartsScreen
import com.radiola.ui.components.MiniPlayer
import com.radiola.ui.favorites.FavoritesScreen
import com.radiola.ui.favorites.FavoritesViewModel
import com.radiola.ui.history.HistoryScreen
import com.radiola.ui.navigation.BottomNavBar
import com.radiola.ui.navigation.NavDestinations
import com.radiola.ui.player.PlayerBottomSheet
import com.radiola.ui.player.PlayerViewModel
import com.radiola.ui.recordings.RecordingsScreen
import com.radiola.ui.settings.SettingsScreen
import com.radiola.ui.stations.StationsScreen
import com.radiola.ui.stations.StationsViewModel
import com.radiola.service.PlayerService
import com.radiola.ui.theme.RadiolaTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@OptIn(ExperimentalMaterial3Api::class)
@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    @Inject
    lateinit var tokenDataStore: TokenDataStore

    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.onCreate(savedInstanceState)
        startService(Intent(this, PlayerService::class.java))
        lifecycleScope.launch {
            tokenDataStore.preload()
        }
        enableEdgeToEdge()
        setContent {
            RadiolaTheme {
                val navController = rememberNavController()
                val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
                var showPlayer by remember { mutableStateOf(false) }
                val playerViewModel: PlayerViewModel = hiltViewModel()
                val stationsViewModel: StationsViewModel = hiltViewModel()
                val favoritesViewModel: FavoritesViewModel = hiltViewModel()
                val isPlaying by playerViewModel.isPlaying.collectAsState()
                val currentStation by playerViewModel.currentStation.collectAsState()
                val currentTrack by playerViewModel.currentTrack.collectAsState()
                val favoriteIds by favoritesViewModel.favoriteIds.collectAsState()
                val stations by stationsViewModel.stations.collectAsState()
                val favorites by favoritesViewModel.favorites.collectAsState()
                val isRecording by playerViewModel.isRecording.collectAsState()
                val isLoggedIn by tokenDataStore.isLoggedIn.collectAsState(initial = false)

                // Авторизация необязательна — всегда стартуем со станций.
                // Вход доступен из Настроек.
                val startDestination = NavDestinations.Stations.route

                val currentRoute = navController
                    .currentBackStackEntryAsState().value?.destination?.route
                val showChrome = currentRoute != NavDestinations.Auth.route

                // Альбомная ориентация: вместо нижнего бара — боковой рейл слева,
                // мини-плеер уезжает под контент. Портрет — прежняя раскладка.
                val landscape = com.radiola.ui.util.isLandscape()

                Scaffold(
                    bottomBar = {
                        if (showChrome && !landscape) {
                            Column(Modifier.navigationBarsPadding()) {
                                if (currentStation != null) {
                                    MiniPlayer(
                                        stationName = currentStation!!.name,
                                        track = currentTrack,
                                        isPlaying = isPlaying,
                                        onClick = { showPlayer = true },
                                        onPlayPause = { playerViewModel.togglePlayPause() }
                                    )
                                    Spacer(Modifier.height(8.dp))
                                }
                                // Навигация доступна и без входа — приложением можно
                                // пользоваться анонимно.
                                BottomNavBar(navController)
                            }
                        }
                    }
                ) { paddingValues ->
                  Row(
                    modifier = Modifier
                        .padding(paddingValues)
                        .fillMaxSize()
                        .then(if (landscape) Modifier.displayCutoutPadding() else Modifier)
                  ) {
                    if (showChrome && landscape) {
                        com.radiola.ui.navigation.SideNavRail(navController)
                    }
                    Column(modifier = Modifier.weight(1f).fillMaxHeight()) {
                    NavHost(
                        navController = navController,
                        startDestination = startDestination,
                        modifier = Modifier.weight(1f).fillMaxWidth(),
                        enterTransition = {
                            androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(220)) +
                                androidx.compose.animation.slideInVertically(
                                    androidx.compose.animation.core.tween(220)
                                ) { it / 24 }
                        },
                        exitTransition = { androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(160)) },
                        popEnterTransition = { androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(220)) },
                        popExitTransition = { androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(160)) }
                    ) {
                        composable(NavDestinations.Stations.route) {
                            StationsScreen(
                                onStationClick = { station ->
                                    playerViewModel.play(station, stations)
                                    showPlayer = true
                                }
                            )
                        }
                        composable(NavDestinations.Charts.route) {
                            ChartsScreen()
                        }
                        composable(NavDestinations.Favorites.route) {
                            FavoritesScreen(
                                onStationClick = { station ->
                                    playerViewModel.play(station, favorites)
                                    showPlayer = true
                                }
                            )
                        }
                        composable(NavDestinations.History.route) {
                            HistoryScreen()
                        }
                        composable(NavDestinations.Recordings.route) {
                            RecordingsScreen()
                        }
                        composable(NavDestinations.Settings.route) {
                            SettingsScreen(
                                onNavigateToAuth = {
                                    navController.navigate(NavDestinations.Auth.route)
                                }
                            )
                        }
                        composable(NavDestinations.Auth.route) {
                            AuthScreen(
                                onAuthSuccess = {
                                    navController.navigate(NavDestinations.Stations.route) {
                                        popUpTo(NavDestinations.Auth.route) { inclusive = true }
                                    }
                                },
                                onSkip = {
                                    navController.navigate(NavDestinations.Stations.route) {
                                        popUpTo(NavDestinations.Auth.route) { inclusive = true }
                                    }
                                }
                            )
                        }
                    }
                    if (showChrome && landscape && currentStation != null) {
                        MiniPlayer(
                            stationName = currentStation!!.name,
                            track = currentTrack,
                            isPlaying = isPlaying,
                            onClick = { showPlayer = true },
                            onPlayPause = { playerViewModel.togglePlayPause() }
                        )
                        Spacer(Modifier.height(12.dp))
                    }
                    } // конец контентной колонки
                  } // конец Row (рейл + контент)
                }

                if (showPlayer) {
                    ModalBottomSheet(
                        onDismissRequest = { showPlayer = false },
                        sheetState = sheetState,
                        containerColor = MaterialTheme.colorScheme.background
                    ) {
                        PlayerBottomSheet(
                            station = currentStation,
                            track = currentTrack,
                            isPlaying = isPlaying,
                            onPlayPause = { playerViewModel.togglePlayPause() },
                            onNext = { playerViewModel.playNext() },
                            onPrevious = { playerViewModel.playPrevious() },
                            isFavorite = currentStation?.let { favoriteIds.contains(it.id) } ?: false,
                            onToggleFavorite = { currentStation?.let { favoritesViewModel.toggleFavorite(it) } },
                            isRecording = isRecording,
                            onToggleRecording = { playerViewModel.toggleRecording() }
                        )
                    }
                }
            }
        }
    }
}
