package com.aiosman.ravenow.ui.composables

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.modifiers.noRippleClickable

/**
 * 全局付费确认对话框组件
 * 参考 iOS 版本的 PointsConfirmDialog
 * 
 * @param cost 需要支付的费用
 * @param currentBalance 当前余额
 * @param balanceAfterCost 支付后余额
 * @param isBalanceSufficient 余额是否充足
 * @param onConfirm 确认支付回调
 * @param onCancel 取消回调
 * @param title 对话框标题
 * @param description 对话框描述
 * @param isProcessing 是否正在处理中
 */
@Composable
fun PointsPaymentDialog(
    cost: Int,
    currentBalance: Int,
    balanceAfterCost: Int,
    isBalanceSufficient: Boolean,
    onConfirm: () -> Unit,
    onCancel: () -> Unit,
    title: String,
    description: String,
    isProcessing: Boolean = false
) {
    val appColors = LocalAppTheme.current
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val dialogWidth = (screenWidth - 48.dp).coerceAtMost(360.dp)
    
    Dialog(
        onDismissRequest = {
            if (!isProcessing) {
                onCancel()
            }
        },
        properties = DialogProperties(
            dismissOnBackPress = !isProcessing,
            dismissOnClickOutside = !isProcessing
        )
    ) {
        Card(
            modifier = Modifier
                .width(dialogWidth)
                .shadow(
                    elevation = 20.dp,
                    shape = RoundedCornerShape(20.dp),
                    spotColor = Color.Black.copy(alpha = 0.2f)
                ),
            shape = RoundedCornerShape(20.dp),
            colors = CardDefaults.cardColors(
                containerColor = appColors.background
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 顶部图标 - 使用 paip_coin_img
                Spacer(modifier = Modifier.height(32.dp))
                Image(
                    painter = painterResource(id = R.mipmap.paip_coin_img),
                    contentDescription = null,
                    modifier = Modifier.size(80.dp),
                    contentScale = ContentScale.Fit
                )
                
                // 标题
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = title,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = appColors.text,
                    textAlign = TextAlign.Center
                )
                
                // 描述
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = description,
                    fontSize = 14.sp,
                    color = appColors.secondaryText,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(horizontal = 20.dp)
                )
                
                // 积分消耗信息区域
                Spacer(modifier = Modifier.height(24.dp))
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(
                            color = appColors.inputBackground.copy(alpha = 0.5f),
                            shape = RoundedCornerShape(12.dp)
                        )
                        .padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 需要消耗
                    CostInfoRow(
                        label = stringResource(R.string.cost_required),
                        amount = cost,
                        appColors = appColors,
                        amountColor = Color(0xFFFF8C00) // 橙色
                    )
                    
                    HorizontalDivider(color = appColors.divider)
                    
                    // 当前余额
                    CostInfoRow(
                        label = stringResource(R.string.current_balance),
                        amount = currentBalance,
                        appColors = appColors,
                        amountColor = if (isBalanceSufficient) appColors.text else Color.Red
                    )
                    
                    HorizontalDivider(color = appColors.divider)
                    
                    // 支付后余额
                    CostInfoRow(
                        label = stringResource(R.string.balance_after),
                        amount = balanceAfterCost,
                        appColors = appColors,
                        amountColor = appColors.text
                    )
                }
                
                // 余额不足提示
                if (!isBalanceSufficient) {
                    Spacer(modifier = Modifier.height(12.dp))
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Warning,
                            contentDescription = null,
                            tint = Color(0xFFFF8C00), // 橙色
                            modifier = Modifier.size(16.dp)
                        )
                        Text(
                            text = stringResource(R.string.insufficient_pai_coin_balance),
                            fontSize = 13.sp,
                            color = Color(0xFFFF8C00), // 橙色
                            textAlign = TextAlign.Center
                        )
                    }
                }
                
                // 按钮
                Spacer(modifier = Modifier.height(24.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 取消按钮
                    Button(
                        onClick = {
                            if (!isProcessing) {
                                onCancel()
                            }
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(50.dp),
                        enabled = !isProcessing,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = appColors.inputBackground,
                            contentColor = appColors.text,
                            disabledContainerColor = appColors.inputBackground,
                            disabledContentColor = appColors.text.copy(alpha = 0.5f)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Text(
                            text = stringResource(R.string.cancel),
                            fontSize = 16.sp,
                            fontWeight = FontWeight.W500
                        )
                    }
                    
                    // 确认按钮
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .height(50.dp)
                            .background(
                                brush = if (isBalanceSufficient) {
                                    Brush.horizontalGradient(
                                        colors = listOf(
                                            appColors.main,
                                            appColors.main
                                        )
                                    )
                                } else {
                                    Brush.horizontalGradient(
                                        colors = listOf(
                                            Color(0xFFFF8C00), // 橙色
                                            Color.Red
                                        )
                                    )
                                },
                                shape = RoundedCornerShape(12.dp)
                            )
                            .then(
                                if (!isProcessing) {
                                    Modifier.noRippleClickable {
                                        if (!isBalanceSufficient) {
                                            // 积分不足，跳转充值页面
                                            onCancel()
                                            // 这里可以发送通知或回调来跳转充值页面
                                        } else {
                                            // 积分充足，确认消费
                                            onConfirm()
                                        }
                                    }
                                } else {
                                    Modifier
                                }
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        if (isProcessing) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(20.dp),
                                color = Color.White,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Text(
                                text = if (isBalanceSufficient) {
                                    stringResource(R.string.confirm_consumption)
                                } else {
                                    stringResource(R.string.go_recharge)
                                },
                                fontSize = 16.sp,
                                fontWeight = FontWeight.W600,
                                color = Color.White,
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(32.dp))
            }
        }
    }
}

/**
 * 费用信息行组件
 */
@Composable
private fun CostInfoRow(
    label: String,
    amount: Int,
    appColors: com.aiosman.ravenow.AppThemeData,
    amountColor: Color? = null
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            fontSize = 14.sp,
            color = appColors.secondaryText
        )
        
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            // 星形图标（参考 iOS 版本）
            Icon(
                imageVector = Icons.Default.Star,
                contentDescription = null,
                modifier = Modifier.size(14.dp),
                tint = Color(0xFFFFD700) // 黄色
            )
            
            Text(
                text = "${amount.formatNumber()}",
                fontSize = 16.sp,
                fontWeight = FontWeight.W600,
                color = amountColor ?: appColors.text
            )
            
            Text(
                text = stringResource(R.string.pai_coin),
                fontSize = 14.sp,
                color = appColors.secondaryText
            )
        }
    }
}

/**
 * 格式化数字，添加千位分隔符
 */
private fun Int.formatNumber(): String {
    return this.toString().reversed().chunked(3).joinToString(",").reversed()
}

