package ru.fincode.tsudesk.presentation.main

import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.CalendarToday
import androidx.compose.material.icons.rounded.Newspaper
import androidx.compose.material.icons.rounded.School
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import ru.fincode.tsudesk.R
import ru.fincode.tsudesk.core.navigation.TopLevelDestination
import ru.fincode.tsudesk.core.navigation.navigateToTopLevel
import ru.fincode.tsudesk.core.ui.components.BottomBarItem
import ru.fincode.tsudesk.core.ui.components.TsudeskBottomBar

@Composable
fun MainScaffold(
    navController: NavHostController,
    content: @Composable (Modifier) -> Unit,
) {
    val scheduleIcon = Icons.Rounded.CalendarToday
    val newsIcon = Icons.Rounded.Newspaper
    val progressIcon = Icons.Rounded.School
    val settingsIcon = Icons.Rounded.Settings

    val items = listOf(
        TopLevelItem(TopLevelDestination.SCHEDULE, R.string.tab_schedule, scheduleIcon),
        TopLevelItem(TopLevelDestination.NEWS, R.string.tab_news, newsIcon),
        TopLevelItem(TopLevelDestination.PROGRESS, R.string.tab_progress, progressIcon),
        TopLevelItem(TopLevelDestination.SETTINGS, R.string.tab_settings, settingsIcon),
    )

    val backStackEntry by navController.currentBackStackEntryAsState()
    val selected = selectedTopLevel(backStackEntry)

    Scaffold(
        contentWindowInsets = WindowInsets(0),
        bottomBar = {
            if (shouldShowBottomBar(backStackEntry)) {
                val uiItems = items.map { item ->
                    BottomBarItem(
                        key = item.destination.name,
                        label = stringResource(item.labelRes),
                        icon = item.icon
                    )
                }

                TsudeskBottomBar(
                    items = uiItems,
                    selectedKey = selected.name,
                    onItemClick = { clicked ->
                        if (clicked.key == selected.name) return@TsudeskBottomBar
                        navController.navigateToTopLevel(
                            TopLevelDestination.valueOf(clicked.key)
                        )
                    }
                )
            }
        }
    ) { innerPadding ->
        content(Modifier.padding(innerPadding))
    }
}