package com.aiosman.ravenow.ui.account

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.modifiers.noRippleClickable

// 星座资源ID列表
val ZODIAC_SIGN_RES_IDS = listOf(
    R.string.zodiac_aries,
    R.string.zodiac_taurus,
    R.string.zodiac_gemini,
    R.string.zodiac_cancer,
    R.string.zodiac_leo,
    R.string.zodiac_virgo,
    R.string.zodiac_libra,
    R.string.zodiac_scorpio,
    R.string.zodiac_sagittarius,
    R.string.zodiac_capricorn,
    R.string.zodiac_aquarius,
    R.string.zodiac_pisces
)

/**
 * 根据星座资源ID获取对应的图片资源ID
 */
fun getZodiacImageResId(zodiacResId: Int): Int {
    return when (zodiacResId) {
        R.string.zodiac_aries -> R.mipmap.baiyang
        R.string.zodiac_taurus -> R.mipmap.jingniu
        R.string.zodiac_gemini -> R.mipmap.shuangzi
        R.string.zodiac_cancer -> R.mipmap.juxie
        R.string.zodiac_leo -> R.mipmap.shizi
        R.string.zodiac_virgo -> R.mipmap.chunv
        R.string.zodiac_libra -> R.mipmap.tiancheng
        R.string.zodiac_scorpio -> R.mipmap.tianxie
        R.string.zodiac_sagittarius -> R.mipmap.sheshou
        R.string.zodiac_capricorn -> R.mipmap.moxie
        R.string.zodiac_aquarius -> R.mipmap.shuiping
        R.string.zodiac_pisces -> R.mipmap.shuangyu
        else -> R.mipmap.xingzuo // 默认使用占位图片
    }
}

/**
 * 根据存储的星座字符串（可能是任何语言）找到对应的资源ID
 * 如果找不到，返回null
 */
@Composable
fun findZodiacResId(storedZodiac: String?): Int? {
    if (storedZodiac.isNullOrEmpty()) return null
    
    // 尝试在所有语言的资源中查找匹配
    ZODIAC_SIGN_RES_IDS.forEachIndexed { index, resId ->
        val zodiacText = stringResource(resId)
        if (zodiacText == storedZodiac) {
            return resId
        }
    }
    
    // 如果找不到精确匹配，尝试通过资源ID索引查找（兼容旧数据）
    // 这里可以根据需要添加更多兼容逻辑
    return null
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ZodiacSelectBottomSheet(
    onClose: () -> Unit
) {
    val appColors = LocalAppTheme.current
    val isDarkMode = AppState.darkMode
    val model = AccountEditViewModel
    val currentZodiacResId = findZodiacResId(model.zodiac)
    val sheetBackgroundColor = if (isDarkMode) {
        appColors.secondaryBackground
    } else {
        Color(0xFFFFFFFF)
    }
    
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    
    // 确保弹窗展开
    LaunchedEffect(Unit) {
        sheetState.expand()
    }
    
    // 监听状态变化，确保弹窗始终展开（防止拖拽关闭和滑动）
    LaunchedEffect(sheetState.currentValue, sheetState.targetValue, sheetState.isVisible) {
        // 如果弹窗被拖拽关闭或位置发生变化，立即重新展开
        if (!sheetState.isVisible || sheetState.targetValue != androidx.compose.material3.SheetValue.Expanded) {
            kotlinx.coroutines.delay(10) // 短暂延迟确保状态更新
            sheetState.expand()
        }
    }

    val statusBarPadding = WindowInsets.systemBars.asPaddingValues()
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    val offsetY = screenHeight * 0.07f - statusBarPadding.calculateTopPadding()
    
    ModalBottomSheet(
        onDismissRequest = onClose,
        sheetState = sheetState,
        containerColor = sheetBackgroundColor, // 根据主题自适应背景
        dragHandle = null
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.95f)
                .offset(y = offsetY)
                .padding(
                    start = 16.dp,
                    end = 16.dp,
                    bottom = 8.dp
                )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight()
            ) {
                // 头部 - 使用 Box 实现绝对居中布局
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    contentAlignment = Alignment.Center
                ) {
                    val cancelButtonGradientColors = if (isDarkMode) {
                        listOf(
                            Color(0xFF3A3A3C),
                            Color(0xFF2C2C2E)
                        )
                    } else {
                        listOf(
                            Color(0xFFFFFFFF),
                            Color(0xFFF8F8F8)
                        )
                    }
                    val cancelButtonContentColor = if (isDarkMode) Color(0xFFFFFFFF) else Color(0xFF404040)

                    // 左上角返回按钮 - 根据 Swift 代码样式，带淡灰色渐变背景
                    Row(
                        modifier = Modifier
                            .align(Alignment.CenterStart)
                            .height(36.dp)
                            .clip(RoundedCornerShape(18.dp)) // 圆角 100.0 在 36dp 高度下接近完全圆角
                            .background(
                                brush = Brush.linearGradient(
                                    colors = cancelButtonGradientColors
                                    // 不指定 start 和 end，默认从左上到右下
                                )
                            )
                            .noRippleClickable { onClose() }
                            .padding(horizontal = 8.dp), // 内部 padding 确保内容不贴边
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 左箭头图标
                        Image(
                            painter = painterResource(id = R.drawable.rider_pro_back_icon),
                            contentDescription = null,
                            modifier = Modifier.size(17.dp),
                            colorFilter = ColorFilter.tint(cancelButtonContentColor)
                        )
                        
                        // "取消" 文字
                        Text(
                            text = "取消",
                            fontSize = 17.sp,
                            fontWeight = FontWeight.Medium,
                            color = cancelButtonContentColor,
                            textAlign = androidx.compose.ui.text.style.TextAlign.Center
                        )
                    }
                    
                    // 中间标题 - 绝对居中
                    Text(
                        text = stringResource(R.string.choose_zodiac),
                        color = appColors.text,
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        textAlign = androidx.compose.ui.text.style.TextAlign.Center
                    )
                }

                Spacer(Modifier.height(12.dp))

                // 创建 NestedScrollConnection 来阻止滚动事件向上传播到 ModalBottomSheet
                val nestedScrollConnection = remember {
                    object : NestedScrollConnection {
                        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                            // 不消费任何事件，让 LazyVerticalGrid 先处理
                            return Offset.Zero
                        }

                        override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
                            // 消费 LazyVerticalGrid 处理后的剩余滚动事件，防止传递到 ModalBottomSheet
                            return available
                        }

                        override suspend fun onPreFling(available: Velocity): Velocity {
                            // 不消费惯性滚动，让 LazyVerticalGrid 先处理
                            return Velocity.Zero
                        }

                        override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
                            // 消费 LazyVerticalGrid 处理后的剩余惯性滚动，防止传递到 ModalBottomSheet
                            return available
                        }
                    }
                }

                // 网格列表 - 2列
                LazyVerticalGrid(
                    columns = GridCells.Fixed(2),
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .nestedScroll(nestedScrollConnection),
                    contentPadding = PaddingValues(
                        start = 8.dp,
                        top = 8.dp,
                        end = 8.dp,
                        bottom = 8.dp
                    ),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(ZODIAC_SIGN_RES_IDS) { index, zodiacResId ->
                        val zodiacText = stringResource(zodiacResId)
                        ZodiacItem(
                            zodiac = zodiacText,
                            zodiacResId = zodiacResId,
                            isSelected = zodiacResId == currentZodiacResId,
                            onClick = {
                                // 保存当前语言的星座文本
                                model.zodiac = zodiacText
                                // 立即保存到本地存储，确保选择后立即生效
                                AppState.UserId?.let { uid ->
                                    com.aiosman.ravenow.AppStore.setUserZodiac(uid, zodiacText)
                                }
                                onClose()
                            }
                        )
                    }
                }
            }
        }
    }
}

// 保留原有的 ZodiacSelectScreen 用于导航路由（如果需要）
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ZodiacSelectScreen() {
    val navController = com.aiosman.ravenow.LocalNavController.current
    ZodiacSelectBottomSheet(
        onClose = {
            navController.navigateUp()
        }
    )
}

@Composable
fun ZodiacItem(
    zodiac: String,
    zodiacResId: Int,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    val appColors = LocalAppTheme.current
    val isDarkMode = AppState.darkMode
    
    // 卡片背景色：浅灰色 (250, 249, 251)
    // 暗色模式下使用比背景色更亮的颜色，以形成对比
    val cardBackgroundColor = if (isDarkMode) {
        Color(0xFF2A2A2A) // 比 secondaryBackground (0xFF1C1C1C) 更亮的灰色
    } else {
        Color(0xFFFAF9FB)
    }
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .aspectRatio(1.1f) // 增加宽高比，使高度相对更低
            .shadow(
                elevation = if (isDarkMode) 8.dp else 2.dp, // 深色模式下更强的阴影
                shape = RoundedCornerShape(21.dp),
                spotColor = if (isDarkMode) Color.Black.copy(alpha = 0.5f) else Color.Black.copy(alpha = 0.1f)
            )
            .clip(RoundedCornerShape(21.dp))
            .background(cardBackgroundColor)
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                onClick()
            }
            .padding(horizontal = 24.dp, vertical = 12.dp), // 减小垂直padding，确保文本不被遮挡
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        // 星座图标 - 使用对应星座的图片
        Box(
            modifier = Modifier.size(100.dp),
            contentAlignment = Alignment.Center
        ) {
            Image(
                painter = painterResource(id = getZodiacImageResId(zodiacResId)),
                contentDescription = zodiac,
                modifier = Modifier.size(100.dp)
            )
        }
        
        // 星座名称 - 使用负间距让文本向上移动，与图标更靠近
        Text(
            text = zodiac,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = appColors.text,
            textAlign = TextAlign.Center,
            modifier = Modifier.offset(y = (-20).dp) // 负间距，让文本进一步向上移动
        )
    }
}

