package eu.gaudian.translator.view.composable

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarColors
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.view.hints.Hint
import eu.gaudian.translator.view.hints.HintBottomSheet
import eu.gaudian.translator.view.hints.LocalShowHints

@Composable
fun AppTopAppBar(
    title: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    onNavigateBack: (() -> Unit)? = null,
    navigationIcon: @Composable (() -> Unit)? = null,
    actions: @Composable RowScope.() -> Unit = {},
    colors: TopAppBarColors = TopAppBarDefaults.topAppBarColors(),
    hintContent: Hint? = null
) {
    val sheetState = rememberModalBottomSheetState()
    var showBottomSheet by remember { mutableStateOf(false) }

    TopAppBar(
        modifier = modifier.height(56.dp),
        windowInsets = WindowInsets(0.dp),
        colors = colors,
        title = {
            Box(
                modifier = Modifier.fillMaxHeight(),
                contentAlignment = Alignment.Center
            ) {
                val showHints = LocalShowHints.current
                if (showHints && hintContent != null) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(modifier = Modifier.weight(1f)) {
                            title()
                        }
                        Box {
                            IconButton(onClick = { showBottomSheet = true }) {
                                Icon(
                                    imageVector = AppIcons.Help,
                                    contentDescription = stringResource(R.string.show_hint),
                                    tint = MaterialTheme.colorScheme.secondary
                                )
                            }
                        }
                    }
                } else {
                    title()
                }
            }
        },
        navigationIcon = {
            if (onNavigateBack != null) {
                Box(
                    modifier = Modifier.fillMaxHeight(),
                    contentAlignment = Alignment.Center
                ) {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            AppIcons.ArrowBack,
                            contentDescription = stringResource(R.string.cd_navigate_back),
                            tint = LocalContentColor.current
                        )
                    }
                }
            } else if (navigationIcon != null) {
                Box(modifier = Modifier.fillMaxHeight(), contentAlignment = Alignment.Center) {
                    navigationIcon()
                }
            } else {
                // No navigation icon
            }
        },
        actions = actions
    )

    if (showBottomSheet) {
        HintBottomSheet(
            onDismissRequest = {
                @Suppress("AssignedValueIsNeverRead")
                showBottomSheet = false
            },
            sheetState = sheetState,
            content = {
                hintContent?.Render()
            }
        )
    }
}


/**
 * A composable that acts as a TopAppBar, containing a back navigation icon
 * and an [AppTabLayout].
 *
 * @param T The type of the tab item, must implement [TabItem].
 * @param tabs The list of tab items to display.
 * @param selectedTab The currently selected tab item.
 * @param onTabSelected Callback function when a tab is selected.
 * @param onNavigateBack Callback function when the back arrow is clicked.
 * @param modifier The modifier to be applied to the layout.
 */
@Composable
fun <T : TabItem> TabbedTopAppBar(
    tabs: List<T>,
    selectedTab: T,
    onTabSelected: (T) -> Unit,
    onNavigateBack: () -> Unit,
    modifier: Modifier = Modifier
) {
    // Use a Surface to provide background color and context for the app bar
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Back navigation icon, similar to its usage in AppTopAppBar
            IconButton(
                onClick = onNavigateBack,
                modifier = Modifier.padding(horizontal = 4.dp)
            ) {
                Icon(
                    imageVector = AppIcons.ArrowBack,
                    contentDescription = stringResource(R.string.cd_navigate_back),
                    tint = MaterialTheme.colorScheme.onSurface
                )
            }

            // The AppTabLayout, taking up the remaining space.
            // Its appearance matches the provided image.
            AppTabLayout(
                tabs = tabs,
                selectedTab = selectedTab,
                onTabSelected = onTabSelected,
                modifier = Modifier.weight(1f)
            )
        }
    }
}

@Suppress("HardCodedStringLiteral")
@ThemePreviews
@Composable
fun TabbedTopAppBarPreview() {
    // Sample data for preview, similar to ModernTabLayoutPreview
    data class SampleTabItem(override val title: String, override val icon: ImageVector) : TabItem

    val tabs = listOf(
        SampleTabItem("All Vocabulary", AppIcons.Home),
        SampleTabItem("Flashcards", AppIcons.Search),
        SampleTabItem("Settings", AppIcons.Settings)
    )

    var selectedTab by remember { mutableStateOf(tabs.first()) }

    MaterialTheme {
        TabbedTopAppBar(
            tabs = tabs,
            selectedTab = selectedTab,
            onTabSelected = { selectedTab = it },
            onNavigateBack = {}
        )
    }
}

@Suppress("HardCodedStringLiteral")
@ThemePreviews
@Composable
fun AppTopAppBarPreview() {
    AppTopAppBar(
        title = { Text("Preview Title") }
    )
}

@ThemePreviews
@Composable
fun AppTopAppBarWithNavigationIconPreview() {
    AppTopAppBar(
        title = { Text(stringResource(R.string.title_title_preview_title)) },
        onNavigateBack = {}
    )
}

@ThemePreviews
@Composable
fun AppTopAppBarWithActionsPreview() {
    AppTopAppBar(
        title = { Text(stringResource(R.string.title_title_preview_title)) },
        actions = {
            IconButton(onClick = {}) {
                Icon(AppIcons.Settings, contentDescription = stringResource(R.string.title_settings))
            }
            IconButton(onClick = {}) {
                AppIcons.ArrowBack
            }
        }
    )
}