package com.laseroptek.raman.ui.screens.main

import android.content.res.Configuration
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.laseroptek.raman.data.datasource.db.RamanDatabase
import com.laseroptek.raman.data.source.db.RamanDatabaseService
import com.laseroptek.raman.navigation.navigationItemsLists
import com.laseroptek.raman.repository.DatabaseRepository
import com.laseroptek.raman.repository.PreferenceRepository
import com.laseroptek.raman.repository.SerialPortRepository
import com.laseroptek.raman.utils.DefaultDispatcherProvider
import com.laseroptek.raman.utils.ext.px
import timber.log.Timber
import com.laseroptek.raman.R

@OptIn(ExperimentalMaterial3WindowSizeClassApi::class, ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    mainNavController: NavHostController = rememberNavController(),
    mainViewModel: MainViewModel = hiltViewModel<MainViewModel>()
) {
    val isInitialized by mainViewModel.isInitialized.collectAsState()
    val keyboardController = LocalSoftwareKeyboardController.current

    DisposableEffect(Unit) {
        onDispose {
            // This is good practice, but not the main fix.
            // It hides the keyboard when this screen is left.
            keyboardController?.hide()
        }
    }

    // It requests focus for the root composable and then hides the keyboard.
    val view = LocalView.current
    LaunchedEffect(Unit) {
        view.post {
            view.clearFocus() // Clear focus from any text field that might have grabbed it.
            keyboardController?.hide()
        }
    }

    /*
    val navBackStackEntry by mainNavController.currentBackStackEntryAsState()
    val currentRoute by remember(navBackStackEntry) {
        derivedStateOf {
            navBackStackEntry?.destination?.route
        }
    }
    */

    // Use Crossfade to prevent the 90-frame layout "snap"
    Crossfade(targetState = isInitialized, label = "init_fade") { ready ->
        if (!ready) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black)
            )
        } else {
            Scaffold(
                topBar = {
                    Spacer(Modifier.height(45.px.dp))
                },
                contentWindowInsets = WindowInsets(0, 0, 0, 0),
                content = { innerPadding ->
                    Timber.d("padding: $innerPadding")
                    Box(modifier = Modifier.fillMaxSize()) {
                        MainView(
                            mainNavController = mainNavController,
                            innerPadding = innerPadding,
                            mainViewModel = mainViewModel,
                            items = navigationItemsLists,
                            onItemClick = { currentNavigationItem ->
                                mainNavController.navigate(currentNavigationItem.route) {
                                    mainNavController.graph.startDestinationRoute?.let { startDestinationRoute ->
                                        popUpTo(startDestinationRoute) {
                                            saveState = true
                                        }
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                            },
                        )
                    }
                }
            )
        }
    }
}


@Preview(
    apiLevel = 34,
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = true,
    device = "spec:width=1920dp,height=1080dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)
@Composable
fun MainScreenPreview(
    mainViewModel:MainViewModel = MainViewModel(
        preferenceRepository = PreferenceRepository(LocalContext.current),
        serialPortRepository = SerialPortRepository.createWithFakeRepository(),
        databaseRepository = DatabaseRepository(RamanDatabaseService(RamanDatabase.getInstance(LocalContext.current))),
        dispatcherProvider = DefaultDispatcherProvider(),
        applicationContext = LocalContext.current
    )
) {
    MainScreen(
        mainViewModel = mainViewModel
    )
}
