package com.example.kmptpc_compose_sample

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import com.example.kmptpc_compose_sample.navigation.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import com.example.kmptpc_compose_sample.demos.material.*
import com.example.kmptpc_compose_sample.demos.material3.*
import com.example.kmptpc_compose_sample.demos.ui.UiBoxDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationBasicTextDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationBasicTextFieldDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationTextSelectionDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationTextFieldSelectionGestureDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationTextFieldScrollDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationLazyColumnDemo
import com.example.kmptpc_compose_sample.demos.foundation.FoundationDragAndDropDemo
import com.example.kmptpc_compose_sample.demos.foundation.SkikoCapabilitiesDemo
import com.example.kmptpc_compose_sample.demos.foundation.OrientationAndSafeAreaDemo
import com.example.kmptpc_compose_sample.demos.navigation.NavigationGestureDemoScreen
import com.example.kmptpc_compose_sample.demos.navigation.NavigationLibraryTestScreen
import com.example.kmptpc_compose_sample.demos.navigation.NavigationTypedRouteDemoScreen

@Composable
internal fun HomeScreen(
    onSelect: (com.example.kmptpc_compose_sample.navigation.ComponentDemo) -> Unit,
    listState: androidx.compose.foundation.lazy.LazyListState,
    searchQuery: String,
    onSearchChange: (String) -> Unit,
    expandedGroups: MutableMap<com.example.kmptpc_compose_sample.navigation.ComposeGroup, Boolean>
) {
    val grouped = com.example.kmptpc_compose_sample.navigation.demosByGroup()
    val filtered = grouped.mapValues { (_, demos) ->
        if (searchQuery.isBlank()) demos
        else demos.filter { d ->
            d.title.contains(searchQuery, ignoreCase = true) ||
            d.id.contains(searchQuery, ignoreCase = true)
        }
    }.filterValues { it.isNotEmpty() || searchQuery.isBlank() }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 8.dp)
    ) {
        // 顶部固定搜索框（避免 iOS LazyColumn 首项兼容性问题）
        Card(backgroundColor = MaterialTheme.colors.surface) {
            OutlinedTextField(
                value = searchQuery,
                onValueChange = onSearchChange,
                label = { Text("搜索") },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                singleLine = true
            )
        }

        Spacer(Modifier.height(12.dp))

        androidx.compose.foundation.lazy.LazyColumn(
            modifier = Modifier.fillMaxSize(),
            state = listState,
            contentPadding = PaddingValues(vertical = 12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            com.example.kmptpc_compose_sample.navigation.ComposeGroup.entries.forEach { group ->
                val demos = filtered[group] ?: emptyList()
                if (demos.isEmpty() && searchQuery.isNotBlank()) {
                    // 搜索无结果时该组隐藏
                } else {
                    val expanded = expandedGroups[group] != false

                    item {
                        Card(
                            backgroundColor = Color.LightGray.copy(alpha = 0.3f), // surfaceVariant replacement
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { expandedGroups[group] = !expanded }
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(12.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Column {
                                    Text(
                                        com.example.kmptpc_compose_sample.navigation.groupTitles[group] ?: group.name,
                                        style = MaterialTheme.typography.h6
                                    )
                                    val countText =
                                        if (searchQuery.isNotBlank()) "匹配：${demos.size}" else "共 ${demos.size} 项"
                                    Text(countText, style = MaterialTheme.typography.caption)
                                }
                                Text(
                                    text = if (expanded) "收起 ▾" else "展开 ▸",
                                    color = MaterialTheme.colors.primary
                                )
                            }
                        }
                    }

                    if (expanded) {
                        items(demos) { demo ->
                            Card(backgroundColor = MaterialTheme.colors.surface) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .clickable { onSelect(demo) }
                                        .padding(16.dp), // Increased padding for better touch target
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Text(demo.title, style = MaterialTheme.typography.body1)
                                }
                            }
                            Divider()
                        }
                    }
                }
            }
        }
    }
}

@Composable
internal fun DemoScreen(demo: ComponentDemo, onBack: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(text = demo.title, style = MaterialTheme.typography.h5)
            OutlinedButton(onClick = onBack) { Text("返回") }
        }
        Divider()

        when (demo.id) {
            // ui
            "ui_box" -> UiBoxDemo()
            // foundation
            "foundation_basic_text" -> FoundationBasicTextDemo()
            "foundation_basic_text_field" -> FoundationBasicTextFieldDemo()
            "foundation_lazy_column" -> FoundationLazyColumnDemo()
            "foundation_haptic_feedback" -> HapticFeedbackTestScreen()
            "foundation_drag_and_drop" -> FoundationDragAndDropDemo()
            "foundation_text_selection" -> FoundationTextSelectionDemo()
            "foundation_text_field_selection_gesture" -> FoundationTextFieldSelectionGestureDemo()
            "foundation_text_field_scroll" -> FoundationTextFieldScrollDemo()
            "skiko_capabilities" -> SkikoCapabilitiesDemo()
            "orientation_safe_area" -> OrientationAndSafeAreaDemo()
            "navigation_animation_test" -> NavigationAnimationTestScreen()
            "navigation_library_test" -> NavigationLibraryTestScreen()
            "navigation_gesture_test" -> NavigationGestureDemoScreen()
            "navigation_typed_route_test" -> NavigationTypedRouteDemoScreen()
            // material
            "material_alert_dialog" -> AlertDialogSamples()
            "material_app_bar" -> AppBarSamples()
            "material_backdrop_scaffold" -> BackdropScaffoldSamples()
            "material_badge" -> BadgeSamples()
            "material_bottom_navigation" -> BottomNavigationSamples()
            "material_bottom_sheet_scaffold" -> BottomSheetScaffoldSamples()
            "material_button_samples" -> ButtonSamples()
            "material_card_samples" -> CardSamples()
            "material_content_alpha" -> ContentAlphaSamples()
            "material_drawer_samples" -> DrawerSamples()
            "material_elevation_samples" -> ElevationSamples()
            "material_exposed_dropdown_menu" -> ExposedDropdownMenuSamples()
            "material_fab_samples" -> FloatingActionButtonSamples()
            "material_icon_button_samples" -> IconButtonSamples()
            "material_list_samples" -> ListSamples()
            "material_menu_samples" -> MenuSamples()
            "material_modal_bottom_sheet" -> ModalBottomSheetSamples()
            "material_navigation_rail" -> NavigationRailSample()
            "material_progress_indicator" -> ProgressIndicatorSamples()
            "material_pull_refresh" -> PullRefreshSamples()
            "material_selection_controls" -> SelectionControlsSamples()
            "material_slider_sample" -> SliderSample()
            "material_surface_samples" -> SurfaceSamples()
            "material_swipeable_samples" -> SwipeableSamples()
            "material_swipe_to_dismiss" -> SwipeToDismissSamples()
            "material_tab_samples" -> TabSamples()
            "material_text_field_samples" -> TextFieldSamples()
            "material_text_samples" -> TextSamples()
            "material_theme_samples" -> ThemeSamples()
            "material_locale_info" -> LocaleInfoDemo()
            "material_text_field_locale" -> TextFieldLocaleComparisonDemo()
            // material3 组（与 Material / Foundation 平级）
            "material3_button" -> Material3ButtonDemo()
            "material3_text_field" -> Material3TextFieldDemo()
            "material3_card" -> Material3CardDemo()
            "material3_alert_dialog" -> Material3AlertDialogDemo()
            "material3_switch" -> Material3SwitchDemo()
            "material3_fab" -> Material3FABDemo()
            "material3_icon_button" -> Material3IconButtonDemo()
            "material3_date_picker" -> Material3DatePickerDemo()
            "material3_date_picker_input" -> Material3DatePickerInputDemo()
            "material3_date_picker_dialog" -> Material3DatePickerDialogDemo()
            "material3_date_range_picker" -> Material3DateRangePickerDemo()
            "lib01" -> Lib01Screen(onBack = onBack)
        }
    }
}

@Composable
internal fun GameEntryPlaceholder() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "小游戏",
            style = MaterialTheme.typography.h5,
            modifier = Modifier.padding(bottom = 12.dp)
        )
        Text(
            text = "功能开发中，敬请期待。",
            style = MaterialTheme.typography.body1,
            color = MaterialTheme.colors.onSurface.copy(alpha = 0.7f)
        )
    }
}

private val haptics = listOf(
    "Confirm (重击)" to HapticFeedbackType.Confirm,
    "Reject (重击)" to HapticFeedbackType.Reject,
    "LongPress (中等)" to HapticFeedbackType.LongPress,
    "ContextClick (中等)" to HapticFeedbackType.ContextClick,
    "TextHandleMove (轻击)" to HapticFeedbackType.TextHandleMove,
    "SegmentTick (轻击)" to HapticFeedbackType.SegmentTick,
    "GestureEnd (轻击)" to HapticFeedbackType.GestureEnd,
    "ToggleOn (轻击)" to HapticFeedbackType.ToggleOn,
    "ToggleOff (轻击)" to HapticFeedbackType.ToggleOff,
    "VirtualKey (轻击)" to HapticFeedbackType.VirtualKey,
)

@Composable
internal fun HapticFeedbackTestScreen() {
    val feedback = LocalHapticFeedback.current

    LazyColumn(
        contentPadding = PaddingValues(16.dp)
    ) {
        items(haptics) { (name, type) ->
            Button(
                onClick = {
                    feedback.performHapticFeedback(type)
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(name)
            }
            Spacer(Modifier.height(16.dp))
        }
    }
}

/** 用于用户测试导航过渡动画：多页之间前进/返回带滑动与淡入淡出。 */
@Composable
internal fun NavigationAnimationTestScreen() {
    var step by remember { mutableStateOf(0) }
    val totalSteps = 3

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text(
            "导航动画测试",
            style = MaterialTheme.typography.h6,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        Text(
            "点击「下一页」/「返回」观察进入与退出动画",
            style = MaterialTheme.typography.caption,
            modifier = Modifier.padding(bottom = 16.dp)
        )

        AnimatedContent(
            targetState = step,
            transitionSpec = {
                if (targetState > initialState) {
                    slideInHorizontally(initialOffsetX = { it }) + fadeIn() togetherWith
                        slideOutHorizontally(targetOffsetX = { -it }) + fadeOut()
                } else {
                    slideInHorizontally(initialOffsetX = { -it }) + fadeIn() togetherWith
                        slideOutHorizontally(targetOffsetX = { it }) + fadeOut()
                }
            },
            label = "navigation_animation",
            contentKey = { it }
        ) { currentStep ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                backgroundColor = MaterialTheme.colors.surface,
                elevation = 4.dp
            ) {
                Column(
                    Modifier
                        .fillMaxSize()
                        .padding(24.dp),
                    verticalArrangement = Arrangement.SpaceBetween
                ) {
                    Column {
                        Text(
                            "第 ${currentStep + 1} 页",
                            style = MaterialTheme.typography.h5
                        )
                        Spacer(Modifier.height(8.dp))
                        Text(
                            "用于验证页面切换时的进入/退出动画是否正常播放。",
                            style = MaterialTheme.typography.body1
                        )
                    }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        OutlinedButton(onClick = { if (step > 0) step-- }) {
                            Text("返回")
                        }
                        Button(
                            onClick = { if (step < totalSteps - 1) step++ }
                        ) {
                            Text("下一页")
                        }
                    }
                }
            }
        }
    }
}
