package com.iscs.bozzys.ui.pages.login

import android.content.Context
import android.content.Intent
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.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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
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.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.iscs.bozzys.R
import com.iscs.bozzys.ui.base.PageBase
import com.iscs.bozzys.ui.pages.home.openPageHome
import com.iscs.bozzys.ui.pages.vm.VMLogin
import com.iscs.bozzys.ui.theme.Main
import com.iscs.bozzys.ui.theme.SubMain
import com.iscs.bozzys.ui.theme.Text
import com.iscs.bozzys.ui.theme.TextDesc
import kotlinx.coroutines.async

/**
 * 打开登录页面
 */
fun Context.openPageLogin() {
    startActivity(Intent(this, PageLogin::class.java))
}

/**
 * 登录页面
 */
class PageLogin : PageBase() {

    @Composable
    override fun GetViews(pv: PaddingValues) {
        val keyboard = LocalSoftwareKeyboardController.current
        Column(
            Modifier
                .fillMaxSize()
                .background(Color.White)
                .clickable(onClick = { keyboard?.hide() }, indication = null, interactionSource = remember { MutableInteractionSource() })
        ) {
            // 顶部显示模块
            Column(
                Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .background(Main),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(
                    Modifier
                        .fillMaxWidth()
                        .weight(3f)
                )
                Text("博士安全能量隔离系统", fontSize = 24.sp, color = Text)
                Spacer(
                    Modifier
                        .fillMaxWidth()
                        .height(8.dp)
                )
                Text("温州博士安全科技有限公司", fontSize = 14.sp, color = TextDesc)
                Spacer(
                    Modifier
                        .fillMaxWidth()
                        .weight(1f)
                )
            }
            Box(
                Modifier
                    .fillMaxSize()
                    .weight(4f)
            ) {
                // 登录输入框布局
                LoginCompose(keyboard)
            }
        }
    }

    @Composable
    fun LoginCompose(kb: SoftwareKeyboardController?, vm: VMLogin = viewModel()) {
        val state = vm.state
        LaunchedEffect(Unit) {
            // 处理基础Toast和Loading提示
            async { vm.toastEvent.showToast() }
            async { vm.loadingEvent.loading() }
        }
        Column(
            Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text("欢迎登录", fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = Text, modifier = Modifier.padding(top = 30.dp))
            Row(
                Modifier
                    .padding(top = 24.dp)
                    .size(335.dp, 47.dp)
                    .border(1.dp, color = Color(0xFFD1D5DB), shape = RoundedCornerShape(12.dp))
                    .clip(RoundedCornerShape(12.dp)),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    "短信登录",
                    Modifier
                        .weight(1f)
                        .fillMaxHeight()
                        .background(if (state.loginType == 0) SubMain else Color.White)
                        .clickable(onClick = { vm.updateLoginType(0) }),
                    color = if (state.loginType == 0) Main else TextDesc,
                    lineHeight = 47.sp,
                    fontSize = 14.sp,
                    fontWeight = if (state.loginType == 0) FontWeight.SemiBold else FontWeight.Normal,
                    textAlign = TextAlign.Center
                )
                Text(
                    "密码登录",
                    Modifier
                        .weight(1f)
                        .fillMaxHeight()
                        .background(if (state.loginType == 1) SubMain else Color.White)
                        .clickable(onClick = { vm.updateLoginType(1) }),
                    color = if (state.loginType == 1) Main else TextDesc,
                    lineHeight = 47.sp,
                    fontSize = 14.sp,
                    fontWeight = if (state.loginType == 1) FontWeight.SemiBold else FontWeight.Normal,
                    textAlign = TextAlign.Center,
                )
            }
            Row(
                Modifier
                    .padding(top = 24.dp)
                    .size(335.dp, 50.dp)
                    .border(1.dp, color = Color(0xFFD1D5DB), shape = RoundedCornerShape(5.dp))
                    .padding(horizontal = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                val resId = if (state.loginType == 0) R.drawable.phone else R.drawable.user
                Icon(painter = painterResource(resId), contentDescription = null, tint = Color(0xFF999999), modifier = Modifier.size(18.dp))
                BasicTextField(
                    state.account,
                    onValueChange = { value ->
                        vm.updateAccount(
                            if (state.loginType == 0) {
                                // 手机号只能输入数字，不能包含小数点
                                value.filter(Char::isDigit)
                            } else {
                                value
                            }
                        )
                    },
                    Modifier
                        .padding(horizontal = 16.dp)
                        .weight(1f),
                    singleLine = true,
                    textStyle = LocalTextStyle.current.copy(fontSize = 16.sp, lineHeight = 20.sp),
                    decorationBox = { innerTextField ->
                        Box(contentAlignment = Alignment.CenterStart) {
                            innerTextField()
                            if (state.account.isEmpty()) {
                                val text = if (state.loginType == 0) "请输入手机号" else "请输入用户名"
                                Text(text, color = Color(0xFF9CA3AF), fontSize = 16.sp, lineHeight = 20.sp, modifier = Modifier.offset(y = (-1).dp))
                            }
                        }
                    },
                    cursorBrush = SolidColor(Main),
                    keyboardOptions = KeyboardOptions(keyboardType = if (state.loginType == 0) KeyboardType.Number else KeyboardType.Email)
                )
            }
            Row(
                Modifier
                    .padding(top = 20.dp)
                    .size(335.dp, 50.dp)
                    .border(1.dp, color = Color(0xFFD1D5DB), shape = RoundedCornerShape(5.dp))
                    .padding(horizontal = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                val resId = if (state.loginType == 0) R.drawable.code else R.drawable.pwd
                Icon(painter = painterResource(resId), contentDescription = null, tint = Color(0xFF999999), modifier = Modifier.size(18.dp))
                BasicTextField(
                    state.code,
                    onValueChange = { value ->
                        vm.updateCode(
                            if (state.loginType == 0) {
                                // 验证码只能输入数字，不能包含小数点
                                value.filter(Char::isDigit)
                            } else {
                                value
                            }
                        )
                    },
                    Modifier
                        .padding(horizontal = 16.dp)
                        .weight(1f),
                    singleLine = true,
                    textStyle = LocalTextStyle.current.copy(fontSize = 16.sp, lineHeight = 20.sp),
                    decorationBox = { innerTextField ->
                        Box(contentAlignment = Alignment.CenterStart) {
                            innerTextField()
                            if (state.code.isEmpty()) {
                                val text = if (state.loginType == 0) "请输入验证码" else "请输入密码"
                                Text(text, color = Color(0xFF9CA3AF), fontSize = 16.sp, lineHeight = 20.sp, modifier = Modifier.offset(y = (-1).dp))
                            }
                        }
                    },
                    cursorBrush = SolidColor(Main),
                    visualTransformation = if (state.loginType == 0) VisualTransformation.None else PasswordVisualTransformation(),
                    keyboardOptions = KeyboardOptions(keyboardType = if (state.loginType == 0) KeyboardType.Number else KeyboardType.Password)
                )
            }
            // 登录按钮
            Button(
                onClick = {
                    // 隐藏输入框
                    kb?.hide()
                    // 执行登录操作
                    vm.login { openPageHome() }
                }, Modifier
                    .padding(top = 30.dp)
                    .size(335.dp, 52.dp)
                    .clip(RoundedCornerShape(5.dp))
                    .background(Main)
            ) {
                Text("登 录", fontSize = 16.sp)
            }
            // 账号提示
            Row(Modifier.padding(top = 16.dp), verticalAlignment = Alignment.CenterVertically) {
                Icon(painter = painterResource(R.drawable.tips), contentDescription = null, tint = Color(0xFF6B7280), modifier = Modifier.size(12.dp))
                Text("工业安全系统，请妥善保管账号信息", Modifier.padding(start = 5.dp), fontSize = 12.sp, color = Color(0xFF6B7280))
            }
            // 其他登录方式
            Box(Modifier.padding(top = 20.dp), contentAlignment = Alignment.Center) {
                Spacer(
                    Modifier
                        .size(335.dp, 1.dp)
                        .background(Color(0xFFEEEEEE))
                )
                Text(
                    "其他登录方式", Modifier
                        .background(Color.White)
                        .padding(horizontal = 5.dp),
                    fontSize = 14.sp, color = Color(0xFF999999)
                )
            }
            Row(Modifier.padding(top = 30.dp, bottom = 10.dp), verticalAlignment = Alignment.CenterVertically) {
                Icon(
                    painter = painterResource(R.drawable.fingerprint),
                    contentDescription = null,
                    Modifier
                        .padding(horizontal = 10.dp)
                        .size(50.dp)
                        .clip(RoundedCornerShape(50))
                        .background(Color(0xFFF5F5F5))
                        .padding(13.dp),
                    tint = Color(0xFF6B7280)
                )
                Icon(
                    painter = painterResource(R.drawable.qrcode),
                    contentDescription = null,
                    Modifier
                        .padding(horizontal = 10.dp)
                        .size(50.dp)
                        .clip(RoundedCornerShape(50))
                        .background(Color(0xFFF5F5F5))
                        .padding(13.dp),
                    tint = Color(0xFF6B7280)
                )
                Icon(
                    painter = painterResource(R.drawable.bluetooth),
                    contentDescription = null,
                    Modifier
                        .padding(horizontal = 10.dp)
                        .size(50.dp)
                        .clip(RoundedCornerShape(50))
                        .background(Color(0xFFF5F5F5))
                        .padding(15.dp),
                    tint = Color(0xFF6B7280)
                )
            }
            Spacer(Modifier.weight(2f))
            // 底部版本等提示
            Column(Modifier.width(335.dp), horizontalAlignment = Alignment.CenterHorizontally) {
                Spacer(
                    Modifier
                        .fillMaxWidth()
                        .height(1.dp)
                        .background(Color(0xFFEEEEEE))
                )
                Text("LOTO智能锁控·能量安全隔离", Modifier.padding(top = 20.dp, bottom = 4.dp), fontSize = 14.sp, color = Color(0xFF666666))
                Text("版本 v1.0.0", Modifier.padding(bottom = 20.dp), fontSize = 14.sp, color = Color(0xFF666666))
            }
            Spacer(Modifier.weight(1f))
        }
    }

}