package com.za.ui.servicing.order_confirm.receive_money


import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.rounded.Phone
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.za.base.theme.bgColor
import com.za.base.theme.black90
import com.za.base.view.CommonButton
import com.za.base.view.CommonDialog
import com.za.base.view.HeadView
import com.za.base.view.LoadError
import com.za.bean.PaymentInfoBean
import com.za.common.GlobalData
import com.za.ext.finish
import com.za.ext.goNextPage
import com.za.ext.noDoubleClick
import com.za.ui.servicing.order_confirm.input_money.InputMoneyActivity
import com.za.ui.servicing.order_confirm.modify_money.ModifyMoneyActivity
import kotlinx.coroutines.delay

val primaryColor = Color(0xFF2563EB)
val backgroundColor = Color(0xFFF8FAFC)


@Preview(showBackground = true)
@Composable
fun PreviewReceiveMoneyScreen() {
    ReceiveMoneyScreen(userOrderId = 1, taskId = 1)
}

@Composable
fun ReceiveMoneyScreen(userOrderId: Int,
                       taskId: Int,
                       vm: ReceiveMoneyVm = viewModel()) {
    val context = LocalContext.current
    val uiState = vm.uiState.collectAsStateWithLifecycle()
    var showSuccessDialog by remember { mutableStateOf(false) }

    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(key1 = lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME) {
                vm.dispatch(action = ReceiveMoneyVm.Action.Init(userOrderId, taskId))
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }


    if (showSuccessDialog) {
        SuccessDialog(
            amount = "${uiState.value.paymentInfoBean?.amount ?: 0.00}",
            onDismiss = { showSuccessDialog = false }
        )
    }

    if (uiState.value.payState == 3) {
        CommonDialog(title = "收款成功", message = "收款成功", cancelEnable = false,
            confirm = {
                goNextPage(GlobalData.currentOrder?.taskState, context)
            }, dismiss = {
                goNextPage(GlobalData.currentOrder?.taskState, context)
            })
    }

    Scaffold(
        topBar = { HeadView(title = "客户收款", onBack = { context.finish() }) },
        bottomBar = {
            AnimatedVisibility(visible = uiState.value.isOnSite == 2) {
                Column {
                    Spacer(modifier = Modifier.height(32.dp))
                    AnimatedVisibility(visible = uiState.value.payState != 1) {
                        CommonButton("发送短信链接") {
                            if (uiState.value.userPhone.isNullOrEmpty()) {
                                ToastUtils.showLong("请输入客户手机号")
                                return@CommonButton
                            }
                            vm.dispatch(ReceiveMoneyVm.Action.CreatePaymentInfo)
                        }
                    }
                }
            }
        }, containerColor = bgColor) {
        // Main Content
        Column(modifier = Modifier
            .fillMaxSize()
            .padding(it)
            .verticalScroll(rememberScrollState())
            .padding(10.dp)) {
            // Amount Section
            AmountSection(paymentInfoBean = uiState.value.paymentInfoBean) {
//                ModifyMoneyActivity.goModifyMoney(context, uiState.value.paymentInfoBean?.userOrderId
//                    ?: 0, uiState.value.paymentInfoBean?.taskOrderId ?: 0)
                ModifyMoneyActivity.goModifyMoney(context, uiState.value.paymentInfoBean?.userOrderId
                    ?: 0, uiState.value.paymentInfoBean?.taskOrderId ?: 0)
            }

            Spacer(modifier = Modifier.height(32.dp))

            if (!uiState.value.paymentInfoBean?.settlementRule.isNullOrBlank()) {
                // Rules Section
                RulesSection(uiState.value.paymentInfoBean?.settlementRule ?: "")
                Spacer(modifier = Modifier.height(32.dp))
            }

            // Action Buttons
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Row(
                    modifier = if (uiState.value.isOnSite == 1) {
                        Modifier
                            .weight(1f)
                            .background(color = primaryColor, shape = RoundedCornerShape(3.dp))
                            .padding(vertical = 15.dp)
                    } else {
                        Modifier
                            .weight(1f)
                            .noDoubleClick {
                                vm.dispatch(ReceiveMoneyVm.Action.ChangeOnSite(1))
                            }
                            .border(1.dp, color = Color.Gray, shape = RoundedCornerShape(3.dp))
                            .padding(vertical = 15.dp)
                    },
                    horizontalArrangement = Arrangement.Center
                ) {
                    if (uiState.value.isOnSite == 1) {
                        Icon(imageVector = Icons.Default.LocationOn, contentDescription = null, tint = Color.White)
                        Text(text = "在现场", color = Color.White)
                    } else {
                        Icon(imageVector = Icons.Default.LocationOn, contentDescription = null, tint = Color.Gray)
                        Text(text = "在现场", color = Color.Gray)
                    }
                }

                Row(
                    modifier = if (uiState.value.isOnSite == 2) {
                        Modifier
                            .weight(1f)
                            .background(color = primaryColor, shape = RoundedCornerShape(3.dp))
                            .padding(vertical = 15.dp)
                    } else {
                        Modifier
                            .weight(1f)
                            .noDoubleClick {
                                vm.dispatch(ReceiveMoneyVm.Action.ChangeOnSite(2))
                            }
                            .border(1.dp, color = Color.Gray, shape = RoundedCornerShape(3.dp))
                            .padding(vertical = 15.dp)
                    },
                    horizontalArrangement = Arrangement.Center
                ) {
                    if (uiState.value.isOnSite == 2) {
                        Icon(imageVector = Icons.Default.Notifications, contentDescription = null, tint = Color.White)
                        Text(text = "不在现场", color = Color.White)
                    } else {
                        Icon(imageVector = Icons.Default.Notifications, contentDescription = null, tint = Color.Gray)
                        Text(text = "不在现场", color = Color.Gray)
                    }
                }
            }

            AnimatedVisibility(visible = uiState.value.isOnSite == 1) {
                Column {
                    Spacer(modifier = Modifier.height(22.dp))
                    QRCodeSection(uiState.value.qrCode ?: "",
                        createPayment = { vm.dispatch(ReceiveMoneyVm.Action.CreatePaymentInfo) })
                }
            }

            AnimatedVisibility(visible = uiState.value.isOnSite == 2) {
                Box(modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 10.dp, vertical = 30.dp)) {
                    OutlinedTextField(
                        value = uiState.value.userPhone ?: "",
                        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Phone),
                        onValueChange = { vm.updateState(uiState.value.copy(userPhone = it)) },
                        label = { Text("请输入客户手机号") },
                        leadingIcon = {
                            Icon(
                                imageVector = Icons.Rounded.Phone,
                                contentDescription = null,
                                tint = primaryColor
                            )
                        },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(12.dp),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = primaryColor,
                            unfocusedBorderColor = Color.Gray,
                            focusedLabelColor = primaryColor,
                            unfocusedLabelColor = Color.Gray),
                        singleLine = true
                    )
                }
            }

            if (uiState.value.payState == 1) {
                Column {
                    Spacer(modifier = Modifier.height(32.dp))
                    CountdownRing { vm.updateState(uiState.value.copy(payState = 4, qrCode = null)) }
                }
            }
        }
    }
}

@Composable
private fun AmountSection(paymentInfoBean: PaymentInfoBean? = null, goModifyMoney: () -> Unit = {}) {
    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
        Text("收款金额", color = Color.Gray, fontSize = 14.sp)
        Spacer(modifier = Modifier.height(8.dp))
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text("￥", fontSize = 30.sp, fontWeight = FontWeight.Medium, color = black90)
            Text("${paymentInfoBean?.amount ?: "0.00"}", fontSize = 36.sp, fontWeight = FontWeight.Medium, color = black90)
            //一口价不允许修改金额
            if (paymentInfoBean?.contractSettleRule != 2) {
                IconButton(onClick = { goModifyMoney() }) {
                    Icon(
                        painter = rememberVectorPainter(Icons.Default.Edit),
                        contentDescription = null,
                        tint = primaryColor
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        Row(
            horizontalArrangement = Arrangement.spacedBy(32.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text("超限单价", color = Color.Gray, fontSize = 14.sp)
                Row(verticalAlignment = Alignment.Top) {
                    Text("￥", fontSize = 16.sp, color = Color.DarkGray)
                    Text("${paymentInfoBean?.unitPrice ?: ""}", fontSize = 16.sp, color = Color.DarkGray)
                    Text("/公里", fontSize = 12.sp, color = Color.Gray)
                }
            }

            VerticalDivider(
                modifier = Modifier
                    .height(32.dp)
                    .width(1.dp),
                color = Color.LightGray
            )

            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text("超限公里数", color = Color.Gray, fontSize = 14.sp)
                Row(verticalAlignment = Alignment.Top) {
                    Text("${paymentInfoBean?.mileage ?: ""}", fontSize = 16.sp, color = Color.DarkGray)
                    Text("公里", fontSize = 12.sp, color = Color.Gray)
                }
            }
        }
    }
}

@Composable
private fun RulesSection(rules: String) {
    Surface(modifier = Modifier.fillMaxWidth(),
        color = backgroundColor,
        shape = RoundedCornerShape(8.dp)) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text("收款规则说明", fontWeight = FontWeight.Medium, fontSize = 12.sp, color = Color.Gray)
            Spacer(modifier = Modifier.height(10.dp))
            RuleItem(rules)
            Spacer(modifier = Modifier.height(10.dp))
        }
    }
}

@Composable
private fun RuleItem(text: String) {
    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) {
        Icon(
            painter = rememberVectorPainter(Icons.Default.CheckCircle),
            contentDescription = null,
            tint = primaryColor,
            modifier = Modifier.size(12.dp)
        )
        Spacer(modifier = Modifier.width(8.dp))
        Text(text, fontSize = 14.sp, color = Color.DarkGray)
    }
}

@Composable
private fun QRCodeSection(qrCode: String? = null, createPayment: () -> Unit = {}) {
    Surface(
        color = backgroundColor,
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {

            if (qrCode.isNullOrEmpty()) {
                LoadError(message = "收款码失效", onRetry = { createPayment() })
            } else {
                Surface(
                    color = Color.White,
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(160.dp)
                            .padding(16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        // Replace with actual QR code image
                        AsyncImage(model = qrCode, contentDescription = null)
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
                Text("请顾客扫码支付", color = Color.Gray, fontSize = 14.sp)
            }
        }
    }
}

@Composable
private fun CountdownRing(outTime: () -> Unit) {
    var countdown by remember { mutableIntStateOf(5 * 60) }
    val progress by animateFloatAsState(
        targetValue = (countdown / 5 * 60) * 360f,
        animationSpec = remember { androidx.compose.animation.core.tween(1000) }
    )

    LaunchedEffect(Unit) {
        while (countdown > 0) {
            delay(1000)
            countdown--
            if (countdown == 0) {
                outTime()
            }
        }
    }

    Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
        Box(modifier = Modifier.size(50.dp), contentAlignment = Alignment.Center) {
            Canvas(modifier = Modifier.fillMaxSize()) {
                drawArc(
                    brush = Brush.sweepGradient(
                        0f to primaryColor,
                        1f to Color.LightGray
                    ),
                    startAngle = -90f,
                    sweepAngle = progress,
                    useCenter = false,
                    style = Stroke(width = 8.dp.toPx(), cap = StrokeCap.Round)
                )
            }
            Surface(
                color = Color.White,
                shape = CircleShape,
                modifier = Modifier.size(50.dp)
            ) {}
            Text(
                text = countdown.toString(),
                fontSize = 20.sp,
                color = black90,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

@Composable
private fun SuccessDialog(amount: String, onDismiss: () -> Unit) {
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            shape = RoundedCornerShape(16.dp),
            color = Color.White
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Box(
                    modifier = Modifier
                        .size(64.dp)
                        .background(primaryColor.copy(alpha = 0.1f), CircleShape)
                        .clip(CircleShape),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        Icons.Default.Check,
                        contentDescription = null,
                        tint = primaryColor,
                        modifier = Modifier.size(32.dp)
                    )
                }
                Spacer(modifier = Modifier.height(16.dp))
                Text("收款成功", fontWeight = FontWeight.Medium, fontSize = 18.sp)
                Text("已收款 ¥$amount", color = Color.Gray, fontSize = 14.sp)
                Spacer(modifier = Modifier.height(16.dp))
                Button(
                    onClick = onDismiss,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("完成")
                }
            }
        }
    }
}