package com.img.rabbit.pages.dialog

import android.Manifest
import android.annotation.SuppressLint
import android.os.Build
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.Row
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.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import com.img.rabbit.R
import kotlinx.coroutines.CoroutineScope

@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun UpdateDialog(
    title: String = "发现新版本~",
    newVersion: String = "V1.0.0",
    desc: String = "修复了一些问题，新增了一些功能",
    url: String,
    scope: CoroutineScope,
    isStartDown: MutableState<Boolean>,
    downProgress: MutableState<Float>,
    onStatusChange: (state: Boolean, isCancel: Boolean, url:String) -> Unit
){
    val storagePermissionState = rememberPermissionState(
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES // Android 13+ 使用具体媒体权限
        } else {
            Manifest.permission.WRITE_EXTERNAL_STORAGE // 旧版本使用常规存储权限
        }
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0x80000000))
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            ) {
                //onStatusChange(false)
            },
        verticalArrangement = Arrangement.Center
    ){
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .padding(horizontal = 36.dp)
                .background(Color.White, shape = RoundedCornerShape(26.dp))
                .align(Alignment.CenterHorizontally)
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ) {
                    //什么都不用做，只是解决点击穿透问题
                }
        ) {
            Image(
                painter = painterResource(id = R.mipmap.ic_dialog_top_mask1),
                contentDescription = null,
                contentScale = ContentScale.FillWidth,
                modifier = Modifier
                    .fillMaxWidth()
            )

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
                    .padding(top = 26.dp)
            ) {
                Text(
                    text = title,
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1A1A1A),
                    modifier = Modifier
                        .wrapContentSize()
                        .align(Alignment.CenterHorizontally)
                )

                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(14.dp)
                )

                Text(
                    text = newVersion,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color(0xFF767676),
                    modifier = Modifier
                        .wrapContentSize()
                        .padding(horizontal = 12.dp)
                        .align(Alignment.CenterHorizontally)
                )

                Text(
                    text = desc,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color(0xFF767676),
                    modifier = Modifier
                        .wrapContentSize()
                        .padding(12.dp)
                )


                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(16.dp)
                )

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 18.dp, end = 18.dp, bottom = 20.dp)
                ) {
                    if(isStartDown.value){
                        Column(
                            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)
                        ) {
                            // 使用 LinearProgressIndicator 显示确定性进度
                            LinearProgressIndicator(
                                progress = { downProgress.value }, // 使用 Lambda 更新进度0~1
                                modifier = Modifier.fillMaxWidth().height(8.dp)
                            )
                            Text(text = "下载进度: ${(downProgress.value * 100).toInt()}%")
                        }


                    }else{

                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentHeight()
                                .weight(1f)
                                .background(
                                    Color(0x00000000),
                                    shape = RoundedCornerShape(359.dp),
                                )
                                .border(
                                    width = 1.dp,
                                    color = Color(0xFF000000),
                                    shape = RoundedCornerShape(359.dp)
                                )
                                .clickable(
                                    indication = null,
                                    interactionSource = remember { MutableInteractionSource() }
                                ) {
                                    onStatusChange(false, true, url)
                                }
                        ) {
                            Text(
                                "暂不",
                                color = Color(0xFF1A1A1A),
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier
                                    .wrapContentWidth()
                                    .wrapContentHeight()
                                    .padding(vertical = 12.dp)
                                    .align(Alignment.Center)
                            )
                        }

                        Box(
                            modifier = Modifier
                                .width(11.dp)
                        )

                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentHeight()
                                .weight(1f)
                                .background(
                                    Color(0xFF252525),
                                    shape = RoundedCornerShape(359.dp),
                                )
                                .clickable(
                                    indication = null,
                                    interactionSource = remember { MutableInteractionSource() }
                                ) {
                                    // 执行下载更新
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                        isStartDown.value = true
                                        onStatusChange(false, false, url)
                                    }else{
                                        when {
                                            // 情况 A：已获得权限
                                            storagePermissionState.status.isGranted -> {
//                                                isStartDown.value = true
                                                onStatusChange(false, false, url)
                                            }
                                            // 情况 B：需要向用户解释（之前拒绝过，但未勾选“不再询问”）
                                            storagePermissionState.status.shouldShowRationale -> {
                                                storagePermissionState.launchPermissionRequest()
                                            }
                                            // 情况 C：从未请求过权限或已被彻底拒绝
                                            else -> {
                                                storagePermissionState.launchPermissionRequest()
                                            }
                                        }
                                    }
                                }
                        ) {
                            Text(
                                "立即更新",
                                color = Color(0xFFC2FF43),
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier
                                    .wrapContentWidth()
                                    .wrapContentHeight()
                                    .padding(vertical = 12.dp)
                                    .align(Alignment.Center)
                            )
                        }
                    }
                }
            }
        }
    }
}
