package com.applemand.zmanim.core.ui

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.PermanentDrawerSheet
import androidx.compose.material3.PermanentNavigationDrawer
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

/**
 * A single navigation destination surfaced in the chrome (rail / bar / drawer).
 */
@Stable
data class AdaptiveDestination(
    val id: String,
    val label: String,
    val icon: ImageVector,
    val selected: Boolean,
    val onClick: () -> Unit,
)

enum class AdaptiveLayoutKind { Compact, Medium, Expanded, ExtraLarge }

fun WindowSizeClass.kind(widthDp: Int): AdaptiveLayoutKind = when {
    widthDp >= 1200 -> AdaptiveLayoutKind.ExtraLarge
    widthSizeClass == WindowWidthSizeClass.Expanded -> AdaptiveLayoutKind.Expanded
    widthSizeClass == WindowWidthSizeClass.Medium -> AdaptiveLayoutKind.Medium
    else -> AdaptiveLayoutKind.Compact
}

val LocalAdaptiveLayout = staticCompositionLocalOf { AdaptiveLayoutKind.Compact }

/**
 * Adaptive scaffold.
 *
 *   Compact     → NavigationBar at bottom, side-panel as ModalBottomSheet.
 *   Medium      → NavigationRail, side-panel inline to the end (collapsible).
 *   Expanded    → PermanentDrawer + side-panel inline.
 *   ExtraLarge  → Same as Expanded but centered within 1400dp.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdaptiveScaffold(
    layout: AdaptiveLayoutKind,
    destinations: List<AdaptiveDestination>,
    topBar: @Composable () -> Unit = {},
    sidePanel: @Composable (() -> Unit)? = null,
    content: @Composable (PaddingValues) -> Unit,
) {
    when (layout) {
        AdaptiveLayoutKind.Compact -> CompactScaffold(destinations, topBar, sidePanel, content)
        AdaptiveLayoutKind.Medium -> MediumScaffold(destinations, topBar, sidePanel, content)
        AdaptiveLayoutKind.Expanded,
        AdaptiveLayoutKind.ExtraLarge -> ExpandedScaffold(
            destinations = destinations,
            topBar = topBar,
            sidePanel = sidePanel,
            content = content,
            maxContentWidth = if (layout == AdaptiveLayoutKind.ExtraLarge) 1400.dp else Int.MAX_VALUE.dp
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CompactScaffold(
    destinations: List<AdaptiveDestination>,
    topBar: @Composable () -> Unit,
    sidePanel: @Composable (() -> Unit)?,
    content: @Composable (PaddingValues) -> Unit,
) {
    var sheetOpen by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    Scaffold(
        topBar = topBar,
        bottomBar = {
            NavigationBar {
                destinations.forEach { d ->
                    NavigationBarItem(
                        selected = d.selected,
                        onClick = d.onClick,
                        icon = { androidx.compose.material3.Icon(d.icon, contentDescription = d.label) },
                        label = { Text(d.label) },
                    )
                }
            }
        },
        content = content,
    )
    if (sheetOpen && sidePanel != null) {
        ModalBottomSheet(onDismissRequest = { sheetOpen = false }) {
            sidePanel()
        }
    }
}

@Composable
private fun MediumScaffold(
    destinations: List<AdaptiveDestination>,
    topBar: @Composable () -> Unit,
    sidePanel: @Composable (() -> Unit)?,
    content: @Composable (PaddingValues) -> Unit,
) {
    Row(Modifier.fillMaxSize()) {
        NavigationRail {
            destinations.forEach { d ->
                NavigationRailItem(
                    selected = d.selected,
                    onClick = d.onClick,
                    icon = { androidx.compose.material3.Icon(d.icon, contentDescription = d.label) },
                    label = { Text(d.label) },
                )
            }
        }
        Column(Modifier.weight(1f)) {
            topBar()
            Box(Modifier.weight(1f)) { content(PaddingValues(0.dp)) }
        }
        if (sidePanel != null) {
            Surface(
                tonalElevation = 1.dp,
                modifier = Modifier
                    .fillMaxHeight()
                    .widthIn(min = 280.dp, max = 360.dp)
            ) {
                Column(Modifier.verticalScroll(rememberScrollState()).padding(12.dp)) {
                    sidePanel()
                }
            }
        }
    }
}

@Composable
private fun ExpandedScaffold(
    destinations: List<AdaptiveDestination>,
    topBar: @Composable () -> Unit,
    sidePanel: @Composable (() -> Unit)?,
    content: @Composable (PaddingValues) -> Unit,
    maxContentWidth: androidx.compose.ui.unit.Dp,
) {
    PermanentNavigationDrawer(
        drawerContent = {
            PermanentDrawerSheet(modifier = Modifier.width(240.dp)) {
                Spacer(Modifier.padding(top = 16.dp))
                destinations.forEach { d ->
                    androidx.compose.material3.NavigationDrawerItem(
                        selected = d.selected,
                        onClick = d.onClick,
                        icon = { androidx.compose.material3.Icon(d.icon, contentDescription = d.label) },
                        label = { Text(d.label) },
                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
                    )
                }
            }
        }
    ) {
        Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
            Row(
                Modifier.widthIn(max = maxContentWidth).fillMaxSize(),
                horizontalArrangement = Arrangement.Center
            ) {
                Column(Modifier.weight(1f)) {
                    topBar()
                    Box(Modifier.weight(1f)) { content(PaddingValues(0.dp)) }
                }
                if (sidePanel != null) {
                    Surface(
                        tonalElevation = 1.dp,
                        modifier = Modifier
                            .fillMaxHeight()
                            .widthIn(min = 320.dp, max = 420.dp)
                    ) {
                        Column(Modifier.verticalScroll(rememberScrollState()).padding(16.dp)) {
                            sidePanel()
                        }
                    }
                }
            }
        }
    }
}
