package com.iscs.bozzys.ui.pages.home

import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
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 androidx.compose.ui.zIndex
import coil.compose.AsyncImage
import com.iscs.bozzys.R
import com.iscs.bozzys.event.AuthEventBus
import com.iscs.bozzys.ui.dialog.TipsDialog
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.profile.openPageProfile
import com.iscs.bozzys.ui.pages.vm.VMHome
import com.iscs.bozzys.ui.theme.Text
import com.iscs.bozzys.utils.BiometricKeyStore
import com.iscs.bozzys.utils.Storage
import com.iscs.bozzys.utils.Storage.saveTokenIv
import com.iscs.bozzys.utils.Storage.saveTokenIvValue
import com.iscs.bozzys.utils.SystemUtil
import com.iscs.bozzys.utils.getRoleName

@OptIn(ExperimentalStdlibApi::class)
@Composable
fun SettingsCompose(pv: PaddingValues, zIndex: Float, vm: VMHome) {
    var showExitDialog by remember { mutableStateOf(false) }
    val ctx = LocalContext.current
    val tokenIv = Storage.readToken()
    // 指纹登录是否可用
    val fingerSupport = false //ctx.isBiometricCanUse() && tokenIv.isNotEmpty()
    Column(
        modifier = Modifier
            .fillMaxSize()
            .zIndex(zIndex)
            .background(MaterialTheme.colorScheme.background)
            .padding(bottom = pv.calculateBottomPadding())
            .pointerInput(Unit) {},
    ) {
        // 顶部状态栏
        TopToolBar(pv, vm)
        // 用户信息
        UserInfo(vm)
        // 开启指纹登录
        if (fingerSupport) CardBox(
            modifier = Modifier
                .padding(horizontal = 16.dp)
                .height(46.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .clickable {
                        if (ctx is Activity) {
                            BiometricKeyStore.createKeyIfNeeded()
                            val cipher = BiometricKeyStore.encryptCipher()
                            cipher.iv.saveTokenIv()
                            SystemUtil.showFingerAuth(ctx, cipher, Storage.readToken().toByteArray()) {
                                it.saveTokenIvValue()
                            }
                        }
                    }
                    .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically
            ) {
                Text("开启指纹登录", fontSize = 14.sp, color = Text)
            }
        }
        Spacer(modifier = Modifier.weight(1f))
        // 底部退出登录
        Button(
            { showExitDialog = true },
            shape = RoundedCornerShape(6.dp),
            modifier = Modifier
                .padding(horizontal = 20.dp, vertical = 10.dp)
                .fillMaxWidth()
                .height(46.dp),
            colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFFA666C))
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text("退出登录", fontSize = 18.sp, fontWeight = FontWeight.Bold)
                Icon(
                    painter = painterResource(R.drawable.logout), contentDescription = null, modifier = Modifier
                        .padding(start = 5.dp)
                        .size(24.dp)
                )
            }
        }
        TipsDialog(show = showExitDialog, content = "确定要退出登录吗？", onCancel = { showExitDialog = false }, onConfirm = {
            showExitDialog = false
            // 退出登录操作
            vm.logout { AuthEventBus.onTokenExpired() }
        })
    }
}

/**
 * 顶部工具栏
 */
@Composable
private fun TopToolBar(pv: PaddingValues, vm: VMHome) {
    val ctx = LocalContext.current
    val state by vm.state.collectAsState()
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(brush = Brush.horizontalGradient(listOf(Color(0xFFFF8C00), Color(0xFFFFA500))))
            .padding(top = pv.calculateTopPadding())
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(66.dp)
                .padding(start = 16.dp, end = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(50)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(R.drawable.user),
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color(0xFFFFD700))
                        .padding(10.dp),
                    contentDescription = null,
                    tint = Color.White
                )
                AsyncImage(model = state.user.avatar, contentDescription = null, modifier = Modifier.fillMaxSize(),contentScale = ContentScale.Crop)
            }
            Column(Modifier.padding(horizontal = 10.dp)) {
                Text("设置", fontSize = 16.sp, lineHeight = 16.sp, fontWeight = FontWeight.Medium, color = Color.White)
                Text("个人中心", fontSize = 12.sp, lineHeight = 12.sp, color = Color.White.copy(alpha = 0.8f))
            }
            Spacer(Modifier.weight(1f))
        }
    }
}

/**
 * 用户信息
 */
@Composable
private fun UserInfo(vm: VMHome) {
    val ctx = LocalContext.current
    val state by vm.state.collectAsState()
    CardBox(modifier = Modifier.padding(16.dp)) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(90.dp)
                .background(brush = Brush.horizontalGradient(listOf(Color(0xFFFFF9E5), Color(0xFFFFFEFB))))
                .clickable { ctx.openPageProfile(state.user) }
                .padding(horizontal = 20.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .background(
                        brush = Brush.linearGradient(
                            colors = listOf(Color(0xFFFFAE00), Color(0xFFF7C700)),
                            start = Offset(0f, 0f),
                            end = Offset.Infinite
                        ),
                        shape = RoundedCornerShape(50)
                    ),
                contentAlignment = Alignment.Center
            ) {
                Text("${state.user.nickname.ifEmpty { "P" }[0]}", color = Text, fontWeight = FontWeight.Bold)
                AsyncImage(
                    model = state.user.avatar,
                    contentDescription = null,
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                // 这里暂时隐藏拍照的图标，整体进入内页修改头像
//                CardContainer(
//                    modifier = Modifier
//                        .size(20.dp)
//                        .align(Alignment.BottomEnd)
//                        .clip(RoundedCornerShape(50))
//                        .background(Color.White)
//                        .padding(5.dp)
//                ) {
//                    Icon(
//                        painter = painterResource(R.drawable.camera),
//                        contentDescription = null, tint = MaterialTheme.colorScheme.primary,
//                        modifier = Modifier.fillMaxSize()
//                    )
//                }
            }
            Column(
                modifier = Modifier
                    .padding(horizontal = 10.dp)
                    .weight(1f)
            ) {
                Text(state.user.nickname, fontWeight = FontWeight.Bold, fontSize = 16.sp, lineHeight = 16.sp, color = Text)
                Text(
                    state.roles.getRoleName(),
                    fontSize = 12.sp,
                    modifier = Modifier
                        .padding(top = 5.dp)
                        .clip(RoundedCornerShape(50))
                        .background(MaterialTheme.colorScheme.primary)
                        .padding(horizontal = 5.dp),
                    color = Color.White
                )
            }
            Icon(
                painter = painterResource(R.drawable.back),
                contentDescription = null,
                modifier = Modifier
                    .size(18.dp)
                    .rotate(180f),
                tint = Color(0xFF999999)
            )
        }
    }
}