package com.aiosman.ravenow.ui.points

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.composables.TabItem
import com.aiosman.ravenow.ui.composables.TabSpacer
import com.aiosman.ravenow.data.PointService
import com.aiosman.ravenow.data.api.PointsChangeLog
import java.text.NumberFormat
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PointsBottomSheet(
    onClose: () -> Unit,
    onRecharge: () -> Unit
){
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val AppColors = LocalAppTheme.current
    val numberFormat = remember { NumberFormat.getNumberInstance(Locale.getDefault()) }
    val balanceState = PointsViewModel.balance.collectAsState(initial = null)

    var tab by remember { mutableStateOf(0) } // 0: history, 1: how to earn

    LaunchedEffect(Unit) {
        PointsViewModel.initLoad()
        // 确保弹窗始终展开
        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 = AppColors.background,
        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
            ) {
                // 左上角返回按钮 - 圆形白色背景，渐变边框，深灰色 ×
                Box(
                    modifier = Modifier
                        .align(Alignment.CenterStart)
                        .size(32.dp)
                        .clip(CircleShape)
                        .drawWithCache {
                            val borderWidth = 1.dp.toPx()
                            // 使用线性渐变，从顶部浅灰到底部白色
                            val gradientBrush = Brush.verticalGradient(
                                colors = listOf(
                                    Color(0xFFE8E8E8),
                                    Color(0xFFF0F0F0),
                                    Color(0xFFF8F8F8),
                                    AppColors.background
                                )
                            )
                            onDrawWithContent {
                                drawContent()
                                drawCircle(
                                    brush = gradientBrush,
                                    radius = size.width / 2 - borderWidth / 2,
                                    center = androidx.compose.ui.geometry.Offset(size.width / 2, size.height / 2),
                                    style = Stroke(width = borderWidth)
                                )
                            }
                        }
                        .background(AppColors.background)
                        .noRippleClickable { onClose() },
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "×",
                        color = AppColors.text,
                        fontSize = 24.sp,
                        fontWeight = FontWeight.Normal
                    )
                }
                
                // 中间标题 - 绝对居中
                Text(
                    text = stringResource(R.string.my_pai_coin),
                    color = AppColors.text,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    textAlign = androidx.compose.ui.text.style.TextAlign.Center
                )
                
                // 右侧充值按钮 - 白色背景，紫色文字，圆角，渐变边框
                Box(
                    modifier = Modifier
                        .align(Alignment.CenterEnd)
                        .clip(RoundedCornerShape(16.dp))
                        .drawWithCache {
                            val borderWidth = 1.dp.toPx()
                            val gradientBrush = Brush.linearGradient(
                                colors = listOf(
                                    Color(0xFFE8E8E8),
                                    Color(0xFFF0F0F0),
                                    Color(0xFFF8F8F8),
                                    AppColors.background
                                )
                            )
                            onDrawWithContent {
                                drawContent()
                                drawRoundRect(
                                    brush = gradientBrush,
                                    topLeft = androidx.compose.ui.geometry.Offset(borderWidth / 2, borderWidth / 2),
                                    size = androidx.compose.ui.geometry.Size(
                                        size.width - borderWidth,
                                        size.height - borderWidth
                                    ),
                                    cornerRadius = CornerRadius(16.dp.toPx()),
                                    style = Stroke(width = borderWidth)
                                )
                            }
                        }
                        .background(AppColors.background)
                        .noRippleClickable { onRecharge() }
                        .padding(horizontal = 12.dp, vertical = 6.dp)
                ) {
                    Text(
                        text = stringResource(R.string.recharge),
                        color = Color(0xFF6B46C1),
                        fontSize = 14.sp,
                        fontWeight = FontWeight.W600
                    )
                }
            }

            Spacer(Modifier.height(12.dp))

            // 余额卡片
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(16.dp))
                    .background(AppColors.nonActive)
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // Current Balance 标签 - 居中
                Text(
                    text = stringResource(R.string.current_balance),
                    color = AppColors.secondaryText,
                    fontSize = 14.sp
                )
                Spacer(Modifier.height(8.dp))
                
                // 余额数值 - 居中，图标在左侧
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.paip_coin_img),
                        contentDescription = "coin",
                        modifier = Modifier
                            .size(28.dp)
                            .clip(CircleShape)
                    )
                    Spacer(Modifier.size(8.dp))
                    Text(
                        text = balanceState.value?.balance?.let { numberFormat.format(it) } ?: "--",
                        color = AppColors.text,
                        fontSize = 36.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
                
                Spacer(Modifier.height(12.dp))
                
                // Total Earned 和 Total Spent - 居中排列
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = numberFormat.format(balanceState.value?.totalEarned ?: 0),
                            color = AppColors.text,
                            fontSize = 18.sp,
                            fontWeight = FontWeight.W700
                        )
                        Spacer(Modifier.height(4.dp))
                        Text(
                            text = stringResource(R.string.total_earned),
                            color = AppColors.secondaryText,
                            fontSize = 12.sp
                        )
                    }
                    Box(
                        modifier = Modifier
                            .height(22.dp)
                            .background(AppColors.divider)
                            .width(1.dp)
                    )
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = numberFormat.format(balanceState.value?.totalSpent ?: 0),
                            color = AppColors.text,
                            fontSize = 18.sp,
                            fontWeight = FontWeight.W700
                        )
                        Spacer(Modifier.height(4.dp))
                        Text(
                            text = stringResource(R.string.total_spent),
                            color = AppColors.secondaryText,
                            fontSize = 12.sp
                        )
                    }
                }
            }

            Spacer(Modifier.height(12.dp))

            // 分段切换
            CustomTabBar(
                selectedTab = tab,
                onTabSelected = { tab = it }
            )

            Spacer(Modifier.height(8.dp))

            // 列表区域
            if (tab == 0) {
                PointsHistoryList(
                    items = PointsViewModel.logs,
                    onLoadMore = { PointsViewModel.loadMore() },
                    hasNext = PointsViewModel.hasNext
                )
            } else {
                HowToEarnList(onRecharge = onRecharge)
            }
            }
        }
    }
}

@Composable
private fun CustomTabBar(
    selectedTab: Int,
    onTabSelected: (Int) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val density = LocalDensity.current
    
    // 外层容器：灰色背景，圆角
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(28.dp)
            .clip(RoundedCornerShape(16.dp))
            .background(Color(0xFFE5E5E5))
    ) {
        // 可滑动的白色背景
        val tabWidth = remember { mutableStateOf(0.dp) }
        val gapWidth = 8.dp
        val animatedOffset by animateDpAsState(
            targetValue = if (selectedTab == 0) 0.dp else tabWidth.value + gapWidth,
            animationSpec = tween(durationMillis = 300),
            label = "tabOffset"
        )
        
        // 白色滑动背景（两侧圆角）
        Box(
            modifier = Modifier
                .fillMaxHeight()
                .width(tabWidth.value)
                .offset(x = animatedOffset)
                .clip(RoundedCornerShape(16.dp))
                .background(AppColors.background)
                .border(
                    width = 1.dp,
                    color = Color(0xFFE5E5E5),
                    shape = RoundedCornerShape(16.dp)
                )
        )
        
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        ) {
            // 交易历史标签（左侧）
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .onSizeChanged { size ->
                        tabWidth.value = with(density) { size.width.toDp() }
                    }
                    .noRippleClickable { onTabSelected(0) },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.transaction_history),
                    color = AppColors.text,
                    fontSize = 15.sp,
                    fontWeight = FontWeight.W600
                )
            }
            
            // 中间灰色填充区域
            Box(
                modifier = Modifier
                    .width(gapWidth)
                    .fillMaxHeight()
            )
            
            // 如何赚取标签（右侧）
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .noRippleClickable { onTabSelected(1) },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.how_to_earn),
                    color = AppColors.text,
                    fontSize = 15.sp,
                    fontWeight = FontWeight.W600
                )
            }
        }
    }
}

// 根据交易原因获取对应的图标资源ID
private fun getIconForReason(reason: String): Int {
    return when (reason) {
        PointService.ChangeReason.EARN_REGISTER -> R.mipmap.group_427319679 // 新用户注册奖励
        PointService.ChangeReason.EARN_DAILY -> R.mipmap.icons_calendar // 每日签到奖励
        PointService.ChangeReason.EARN_INVITE -> R.mipmap.icons_users // 邀请好友奖励
        PointService.ChangeReason.EARN_TASK -> R.mipmap.icons_task // 任务完成奖励
        PointService.ChangeReason.EARN_RECHARGE -> R.mipmap.icons_credit_card // 充值获得
        else -> R.mipmap.paip_coin_img // 其他类型使用默认图标
    }
}

@Composable
private fun PointsHistoryList(
    items: List<PointsChangeLog>,
    onLoadMore: () -> Unit,
    hasNext: Boolean
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val numberFormat = remember { NumberFormat.getNumberInstance(Locale.getDefault()) }
    val listState = rememberLazyListState()
    val loading = PointsViewModel.loading
    var lastLoadTriggeredIndex by remember { mutableStateOf(-1) }
    var previousItemsSize by remember { mutableStateOf(items.size) }

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

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

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

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

    // 当数据加载完成后，重置触发索引，以便可以继续加载
    LaunchedEffect(items.size, loading) {
        if (items.size > previousItemsSize && !loading) {
            // 数据已加载完成，重置触发索引
            lastLoadTriggeredIndex = -1
            previousItemsSize = items.size
        } else if (items.size != previousItemsSize) {
            previousItemsSize = items.size
        }
    }

    // 监听滚动位置，接近底部时自动加载更多
    LaunchedEffect(Unit) {
        snapshotFlow { 
            listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
        }
            .debounce(500) // 防抖500ms，等待滚动停止后再触发，避免快速滚动时频繁触发
            .distinctUntilChanged() // 只在值变化时触发
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex >= 0 && hasNext && !loading) {
                    val totalItems = items.size
                    // 当滚动到倒数第3个item时，触发加载更多
                    // 并且确保不会重复触发（检查上次触发的索引）
                    if (totalItems > 0 && 
                        lastVisibleIndex >= totalItems - 3 && 
                        lastVisibleIndex != lastLoadTriggeredIndex) {
                        lastLoadTriggeredIndex = lastVisibleIndex
                        onLoadMore()
                    }
                }
            }
    }

    LazyColumn(
        state = listState,
        modifier = Modifier
            .fillMaxWidth()
            .nestedScroll(nestedScrollConnection)
    ) {
        items(items) { item ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 10.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    // 根据交易类型显示对应图标
                    val iconResId = getIconForReason(item.reason ?: "")
                    Image(
                        painter = painterResource(id = iconResId),
                        contentDescription = "reason",
                        modifier = Modifier
                            .size(40.dp)
                            .clip(RoundedCornerShape(12.dp))
                    )
                    Spacer(Modifier.size(12.dp))
                    Column {
                        Text(text = PointService.getReasonDescription(context, item.reason ?: "" ), color = AppColors.text, fontSize = 16.sp, fontWeight = FontWeight.W600)
                        Spacer(Modifier.height(4.dp))
                        Text(text = item.createdAt ?: "", color = AppColors.secondaryText, fontSize = 12.sp)
                    }
                }
                val amount = item.amount ?: 0
                val isPositive = amount >= 0
                val amountColor = if (isPositive) Color(0xFF00C853) else Color(0xFFFF1744)
                Text(
                    text = (if (isPositive) "+" else "") + numberFormat.format(amount),
                    color = amountColor,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
        // 显示加载状态
        if (loading && items.isNotEmpty()) {
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.load_more),
                        color = AppColors.secondaryText,
                        fontSize = 14.sp
                    )
                }
            }
        }
        // 显示已经到底提示
        if (!hasNext && items.isNotEmpty()) {
            item {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "已经到底",
                        color = AppColors.secondaryText,
                        fontSize = 14.sp
                    )
                }
            }
        }
    }
}

// 图标类型枚举
private enum class EarnIconType {
    GIFT_BOX,      // 新用户奖励 - 橙色礼物盒
    CALENDAR,      // 每日签到 - 蓝色日历
    PEOPLE,        // 邀请好友 - 蓝色人物
    CHECKMARK,     // 完成任务 - 紫色对勾
    CARDS          // 充值派币 - 紫色卡片
}

// 赚取方式数据类
private data class EarnMethod(
    val title: String,
    val desc: String,
    val reward: String,
    val iconColor: Color,
    val iconBackgroundColor: Color,
    val iconType: EarnIconType,
    val isClickable: Boolean = false,
    val onClick: (() -> Unit)? = null
)

@Composable
private fun HowToEarnList(onRecharge: () -> Unit) {
    val AppColors = LocalAppTheme.current

    val earnMethods = listOf(
        EarnMethod(
            title = stringResource(R.string.new_user_reward),
            desc = stringResource(R.string.new_user_reward_desc),
            reward = "+500",
            iconColor = Color(0xFFFF8D28), // RGB(255, 141, 40)
            iconBackgroundColor = Color(0xFFFF8D28).copy(alpha = 0.06f),
            iconType = EarnIconType.GIFT_BOX
        ),
        EarnMethod(
            title = stringResource(R.string.daily_check_in),
            desc = stringResource(R.string.daily_check_in_desc),
            reward = "+10-50",
            iconColor = Color(0xFF00C0E8), // RGB(0, 192, 232)
            iconBackgroundColor = Color(0xFF00C0E8).copy(alpha = 0.06f),
            iconType = EarnIconType.CALENDAR
        ),
        EarnMethod(
            title = stringResource(R.string.invite_friends),
            desc = stringResource(R.string.invite_friends_desc),
            reward = "+100",
            iconColor = Color(0xFF00C0E8), // RGB(0, 192, 232)
            iconBackgroundColor = Color(0xFF00C0E8).copy(alpha = 0.06f),
            iconType = EarnIconType.PEOPLE
        ),
        EarnMethod(
            title = stringResource(R.string.complete_tasks),
            desc = stringResource(R.string.complete_tasks_desc),
            reward = "+20-200",
            iconColor = Color(0xFFCB30E0), // RGB(203, 48, 224)
            iconBackgroundColor = Color(0xFFCB30E0).copy(alpha = 0.06f),
            iconType = EarnIconType.CHECKMARK
        ),
        EarnMethod(
            title = stringResource(R.string.recharge_pai_coin),
            desc = stringResource(R.string.recharge_pai_coin_desc),
            reward = ">",
            iconColor = Color(0xFF6155F5), // RGB(97, 85, 245)
            iconBackgroundColor = Color(0xFF6155F5).copy(alpha = 0.06f),
            iconType = EarnIconType.CARDS,
            isClickable = true,
            onClick = onRecharge
        )
    )

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

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

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

            override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
                // 消费 LazyColumn 处理后的剩余惯性滚动，防止传递到 ModalBottomSheet
                return available
            }
        }
    }
    
    LazyColumn(
        modifier = Modifier
            .fillMaxWidth()
            .nestedScroll(nestedScrollConnection),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        items(earnMethods) { method ->
            EarnMethodCard(
                method = method,
                AppColors = AppColors
            )
        }
    }
}

@Composable
private fun EarnMethodCard(
    method: EarnMethod,
    AppColors: com.aiosman.ravenow.AppThemeData
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(AppColors.nonActive)
            .then(
                if (method.isClickable) {
                    Modifier.clickable { method.onClick?.invoke() }
                } else {
                    Modifier
                }
            )
            .padding(horizontal = 16.dp, vertical = 10.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.weight(1f)
        ) {
            // 图标背景
            Box(
                modifier = Modifier
                    .size(50.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(method.iconBackgroundColor),
                contentAlignment = Alignment.Center
            ) {
                CustomIcon(
                    iconType = method.iconType,
                    color = method.iconColor
                )
            }
            Spacer(modifier = Modifier.size(12.dp))
            Column {
                Text(
                    text = method.title,
                    color = AppColors.text,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = method.desc,
                    color = AppColors.secondaryText,
                    fontSize = 12.sp
                )
            }
        }

        // 奖励或箭头
        if (method.reward == ">") {
            Image(
                painter = painterResource(id = R.drawable.rider_pro_back_icon),
                contentDescription = "Navigate",
                modifier = Modifier
                    .size(16.dp)
                    .rotate(180f),
                colorFilter = ColorFilter.tint(AppColors.secondaryText)
            )
        } else {
            Text(
                text = method.reward,
                color = Color(0xFF00C853),
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Composable
private fun CustomIcon(
    iconType: EarnIconType,
    color: Color,
    modifier: Modifier = Modifier
) {
    val iconResId = when (iconType) {
        EarnIconType.GIFT_BOX -> R.mipmap.group_427319679
        EarnIconType.CALENDAR -> R.mipmap.icons_calendar
        EarnIconType.PEOPLE -> R.mipmap.icons_users
        EarnIconType.CHECKMARK -> R.mipmap.icons_task
        EarnIconType.CARDS -> R.mipmap.icons_credit_card
    }
    
    Image(
        painter = painterResource(id = iconResId),
        contentDescription = null,
        modifier = modifier
    )
}

@Composable
private fun GiftBoxIcon(color: Color) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        val strokeWidth = 2.dp.toPx()
        val size = size.width
        
        // 礼物盒主体 (17.1 x 14.0)
        val boxWidth = size * 0.71f
        val boxHeight = size * 0.58f
        val boxLeft = (size - boxWidth) / 2
        val boxTop = size * 0.14f
        
        // 填充背景
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(boxLeft, boxTop),
            size = androidx.compose.ui.geometry.Size(boxWidth, boxHeight)
        )
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(boxLeft, boxTop),
            size = androidx.compose.ui.geometry.Size(boxWidth, boxHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 顶部横线 (17.1 x 2.0)
        val lineWidth = boxWidth
        val lineHeight = size * 0.08f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(boxLeft, boxTop),
            size = androidx.compose.ui.geometry.Size(lineWidth, lineHeight)
        )
        
        // 左侧竖线 (2.0 x 14.0)
        val verticalLineWidth = size * 0.08f
        val verticalLineHeight = boxHeight
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(boxLeft, boxTop),
            size = androidx.compose.ui.geometry.Size(verticalLineWidth, verticalLineHeight)
        )
        
        // 顶部两个小盒子 (7.2 x 5.3)
        val smallBoxWidth = size * 0.3f
        val smallBoxHeight = size * 0.22f
        val smallBoxY = size * 0.29f
        
        // 右侧小盒子
        val rightBoxLeft = boxLeft + boxWidth * 0.21f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(rightBoxLeft, smallBoxY),
            size = androidx.compose.ui.geometry.Size(smallBoxWidth, smallBoxHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 左侧小盒子
        val leftBoxLeft = boxLeft - boxWidth * 0.21f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(leftBoxLeft, smallBoxY),
            size = androidx.compose.ui.geometry.Size(smallBoxWidth, smallBoxHeight),
            style = Stroke(width = strokeWidth)
        )
    }
}

@Composable
private fun CalendarIcon(color: Color) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        val strokeWidth = 2.dp.toPx()
        val size = size.width
        
        // 日历主体 (19.4 x 18.2)
        val calendarWidth = size * 0.81f
        val calendarHeight = size * 0.76f
        val calendarLeft = (size - calendarWidth) / 2
        val calendarTop = size * 0.05f
        
        // 顶部横条 (19.1 x 5.8)
        val topBarWidth = size * 0.8f
        val topBarHeight = size * 0.24f
        val topBarTop = size * 0.22f
        
        // 填充背景
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(calendarLeft, topBarTop),
            size = androidx.compose.ui.geometry.Size(topBarWidth, topBarHeight)
        )
        
        // 日历主体填充
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(calendarLeft, calendarTop),
            size = androidx.compose.ui.geometry.Size(calendarWidth, calendarHeight)
        )
        
        // 日历主体描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(calendarLeft, calendarTop),
            size = androidx.compose.ui.geometry.Size(calendarWidth, calendarHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 顶部横条描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(calendarLeft, topBarTop),
            size = androidx.compose.ui.geometry.Size(topBarWidth, topBarHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 顶部横线 (19.1 x 2.0)
        val lineWidth = topBarWidth
        val lineHeight = size * 0.1f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(calendarLeft, topBarTop + topBarHeight - lineHeight),
            size = androidx.compose.ui.geometry.Size(lineWidth, lineHeight)
        )
        
        // 两个小圆点 (2.0 x 4.0)
        val dotWidth = size * 0.08f
        val dotHeight = size * 0.17f
        val dotY = size * 0.17f
        
        // 左侧圆点
        val leftDotLeft = calendarLeft - size * 0.19f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(leftDotLeft, dotY),
            size = androidx.compose.ui.geometry.Size(dotWidth, dotHeight)
        )
        
        // 右侧圆点
        val rightDotLeft = calendarLeft + calendarWidth - dotWidth + size * 0.175f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(rightDotLeft, dotY),
            size = androidx.compose.ui.geometry.Size(dotWidth, dotHeight)
        )
    }
}

@Composable
private fun PeopleIcon(color: Color) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        val strokeWidth = 2.dp.toPx()
        val size = size.width
        
        // 左侧人物头部 (8.0 x 8.0)
        val headSize = size * 0.33f
        val headLeft = size * 0.1f
        val headTop = size * 0.23f
        
        // 填充背景
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(headLeft, headTop),
            size = androidx.compose.ui.geometry.Size(headSize, headSize)
        )
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(headLeft, headTop),
            size = androidx.compose.ui.geometry.Size(headSize, headSize),
            style = Stroke(width = strokeWidth)
        )
        
        // 左侧身体 (3.0 x 6.0)
        val bodyWidth = size * 0.125f
        val bodyHeight = size * 0.25f
        val leftBodyLeft = headLeft + headSize + size * 0.1f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(leftBodyLeft, headTop),
            size = androidx.compose.ui.geometry.Size(bodyWidth, bodyHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 右侧人物头部 (14.0 x 8.0)
        val rightHeadWidth = size * 0.58f
        val rightHeadHeight = headSize
        val rightHeadLeft = headLeft
        val rightHeadTop = headTop + headSize + size * 0.1f
        
        // 填充背景
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(rightHeadLeft, rightHeadTop),
            size = androidx.compose.ui.geometry.Size(rightHeadWidth, rightHeadHeight)
        )
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(rightHeadLeft, rightHeadTop),
            size = androidx.compose.ui.geometry.Size(rightHeadWidth, rightHeadHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 右侧身体 (3.0 x 4.9)
        val rightBodyWidth = bodyWidth
        val rightBodyHeight = size * 0.2f
        val rightBodyLeft = rightHeadLeft + rightHeadWidth - rightBodyWidth + size * 0.1f
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(rightBodyLeft, rightHeadTop),
            size = androidx.compose.ui.geometry.Size(rightBodyWidth, rightBodyHeight),
            style = Stroke(width = strokeWidth)
        )
    }
}

@Composable
private fun CheckmarkIcon(color: Color) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        val strokeWidth = 2.dp.toPx()
        val size = size.width
        
        // 方框 (15.6 x 17.1)
        val boxWidth = size * 0.65f
        val boxHeight = size * 0.71f
        val boxLeft = (size - boxWidth) / 2
        val boxTop = size * 0.05f
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(boxLeft, boxTop),
            size = androidx.compose.ui.geometry.Size(boxWidth, boxHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 顶部横条 (9.0 x 4.7)
        val topBarWidth = size * 0.375f
        val topBarHeight = size * 0.2f
        val topBarLeft = (size - topBarWidth) / 2
        val topBarTop = size * 0.31f
        
        // 填充背景
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(topBarLeft, topBarTop),
            size = androidx.compose.ui.geometry.Size(topBarWidth, topBarHeight)
        )
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(topBarLeft, topBarTop),
            size = androidx.compose.ui.geometry.Size(topBarWidth, topBarHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 对勾圆圈 (6.0 x 6.0)
        val circleSize = size * 0.25f
        val circleLeft = (size - circleSize) / 2
        val circleTop = boxTop + boxHeight * 0.12f
        
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(circleLeft, circleTop),
            size = androidx.compose.ui.geometry.Size(circleSize, circleSize),
            style = Stroke(width = strokeWidth)
        )
    }
}

@Composable
private fun CardsIcon(color: Color) {
    androidx.compose.foundation.Canvas(
        modifier = Modifier.fillMaxSize()
    ) {
        val strokeWidth = 2.dp.toPx()
        val size = size.width
        
        // 底层卡片 (16.1 x 13.0)
        val bottomCardWidth = size * 0.67f
        val bottomCardHeight = size * 0.54f
        val bottomCardLeft = size * 0.067f
        val bottomCardTop = size * 0.08f
        
        // 填充背景
        drawRect(
            color = color.copy(alpha = 0.2f),
            topLeft = androidx.compose.ui.geometry.Offset(bottomCardLeft, bottomCardTop),
            size = androidx.compose.ui.geometry.Size(bottomCardWidth, bottomCardHeight)
        )
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(bottomCardLeft, bottomCardTop),
            size = androidx.compose.ui.geometry.Size(bottomCardWidth, bottomCardHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 顶层卡片 (15.8 x 11.8)
        val topCardWidth = size * 0.66f
        val topCardHeight = size * 0.49f
        val topCardLeft = size * 0.075f
        val topCardTop = size * 0.1f
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(topCardLeft, topCardTop),
            size = androidx.compose.ui.geometry.Size(topCardWidth, topCardHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 顶部横条 (16.1 x 4.6)
        val topBarWidth = bottomCardWidth
        val topBarHeight = size * 0.19f
        val topBarLeft = bottomCardLeft
        val topBarTop = bottomCardTop
        
        // 描边
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(topBarLeft, topBarTop),
            size = androidx.compose.ui.geometry.Size(topBarWidth, topBarHeight),
            style = Stroke(width = strokeWidth)
        )
        
        // 小圆点 (2.7 x 2.0)
        val dotWidth = size * 0.11f
        val dotHeight = size * 0.08f
        val dotLeft = bottomCardLeft + bottomCardWidth * 0.32f
        val dotTop = bottomCardTop + bottomCardHeight * 0.2f
        
        drawRect(
            color = color,
            topLeft = androidx.compose.ui.geometry.Offset(dotLeft, dotTop),
            size = androidx.compose.ui.geometry.Size(dotWidth, dotHeight)
        )
    }
}
