package ru.fincode.tsudesk.presentation.main

import androidx.compose.foundation.layout.padding
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.painterResource
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import ru.fincode.core.ui.components.BottomBarItem
import ru.fincode.core.ui.components.TsudeskBottomBar
import ru.fincode.tsudesk.R
import ru.fincode.tsudesk.core.navigation.TopLevelDestination
import ru.fincode.tsudesk.core.navigation.navigateToTopLevel

@Composable
fun MainScaffold(
    navController: NavHostController,
    content: @Composable (Modifier) -> Unit,
) {
    val scheduleIcon = painterResource(R.drawable.ic_progress)
    val newsIcon = painterResource(R.drawable.ic_news)
    val progressIcon = painterResource(R.drawable.ic_progress)
    val settingsIcon = painterResource(R.drawable.ic_progress)

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

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

    Scaffold(
        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))
    }
}