package theorycrafter.ui.market

import androidx.compose.foundation.layout.*
import androidx.compose.material.SnackbarHostState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.WindowPosition
import compose.utils.requestInitialFocus
import eve.data.EveItemType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import theorycrafter.*
import theorycrafter.ui.EveItemTypeInfo
import theorycrafter.ui.ItemInfoPage
import theorycrafter.ui.LocalSnackbarHost
import theorycrafter.ui.TheorycrafterTheme
import theorycrafter.ui.widgets.SearchField
import theorycrafter.ui.widgets.ThreePanelScaffold


/**
 * The market tree window.
 */
@Composable
fun MarketTreeWindow() {
    val windowManager = LocalTheorycrafterWindowManager.current
    val state = windowManager.marketTreeWindowState
    if (state !is SimpleSavedWindowState.Open)
        return

    val windowState = rememberWindowStateAndUpdateSettings(
        windowSettings = state.windowSettings,
        defaultPosition = { WindowPosition.PlatformDefault },
        defaultSize = { TheorycrafterTheme.sizes.marketTreeWindowDefaultSize },
    )

    TheorycrafterWindow(
        title = "Market",
        onCloseRequest = windowManager::closeMarketTreeWindow,
        state = windowState
    ) {
        MarketTreeWindowContent(Modifier.fillMaxSize())

        LaunchedEffect(state, window) {
            state.window = window
        }
    }
}


/**
 * The item info pages to show.
 */
private val ItemInfoPages = listOf(ItemInfoPage.Overview, ItemInfoPage.Attributes, ItemInfoPage.SkillRequirements)


/**
 * The content of the market tree window.
 */
@Composable
private fun MarketTreeWindowContent(modifier: Modifier) {
    val snackbarHost = remember { SnackbarHostState() }
    CompositionLocalProvider(LocalSnackbarHost provides snackbarHost) {
        var displayedMarketGroupItem: MarketTreeGroupItem? by remember { mutableStateOf(null) }
        ThreePanelScaffold(
            modifier = modifier,
            left = {
                MarketTreeWithSearchField(
                    onLeafMarketGroupSelected = { displayedMarketGroupItem = it },
                    modifier = Modifier
                        .width(TheorycrafterTheme.sizes.marketTreeWidth)
                        .fillMaxHeight()
                )
            },
            middle = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(TheorycrafterTheme.spacing.medium)
                ) {
                    var selectedItemType: EveItemType? by remember { mutableStateOf(null) }
                    val itemTypes = remember(displayedMarketGroupItem) {
                        displayedMarketGroupItem?.itemTypes
                    }
                    MarketGroupItemsList(
                        itemTypes = itemTypes,
                        marketGroup = displayedMarketGroupItem?.marketGroup,
                        onItemTypeSelected = { selectedItemType = it },
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(3f)
                    )
                    EveItemTypeInfo(
                        itemType = selectedItemType,
                        pages = ItemInfoPages,
                        selectedBackground = TheorycrafterTheme.colors.threePanelScaffold().sideBackground,
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(2f)
                    )
                }
            },
            snackbarHostState = snackbarHost
        )
    }
}


/**
 * The market tree with a search field for filtering items.
 */
@Composable
private fun MarketTreeWithSearchField(
    onLeafMarketGroupSelected: (MarketTreeGroupItem) -> Unit,
    modifier: Modifier,
) {
    Column(
        modifier = modifier,
    ) {
        var searchText by remember { mutableStateOf("") }
        SearchField(
            searchText = searchText,
            onSearched = { searchText = it },
            placeholderText = "Item name",
            modifier = Modifier
                .fillMaxWidth()
                .padding(
                    top = TheorycrafterTheme.spacing.verticalEdgeMargin,
                    bottom = TheorycrafterTheme.spacing.small
                )
                .padding(horizontal = TheorycrafterTheme.spacing.horizontalEdgeMargin),
            textFieldModifier = Modifier.requestInitialFocus()
        )

        val allItemsAutoSuggest = TheorycrafterContext.autoSuggest.allMarketItems
        val filteredItems = produceState<Set<EveItemType>?>(
            initialValue = null,
            key1 = searchText,
        ) {
            withContext(Dispatchers.Default) {
                value = allItemsAutoSuggest(searchText)?.toSet()
            }
        }.value
        MarketTree(
            onLeafMarketGroupSelected = onLeafMarketGroupSelected,
            itemFilter = { filteredItems?.contains(it) ?: true },
            initiallyAllExpanded = filteredItems != null,
            modifier = Modifier
                .weight(1f)
        )
    }
}