package com.lanyun.wanglaotou.composable

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.lanyun.wanglaotou.R
import com.lanyun.wanglaotou.ui.theme.c_B3F
import com.lanyun.wanglaotou.viewModel.LoginAndRegViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lanyun.wanglaotou.public.*
import com.lanyun.wanglaotou.viewModel.LoginViewAction
import com.lanyun.wanglaotou.viewModel.LoginViewEvent
import com.lanyun.wanglaotou.viewModel.MainViewModel


@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun LoginCompose(
        navHostController: NavHostController,
        mainViewModel: MainViewModel,
        viewModel: LoginAndRegViewModel = viewModel()
) {
        val viewStates = viewModel.viewStates
        val keyboardController = LocalSoftwareKeyboardController.current
        val coroutineState = rememberCoroutineScope()

        LaunchedEffect(Unit) {
                viewModel.viewEvents.collect {
                        if (it is LoginViewEvent.PopBack) {
                                navHostController.navigateUp()
                        } else if (it is LoginViewEvent.ErrorMessage) {

                        }
                }
        }

        LoginScreen(mainViewModel,viewModel,navHostController,keyboardController)
}


/**
 * 登录页面 布局
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun LoginScreen(
        mainViewModel: MainViewModel,
        loginModel: LoginAndRegViewModel,
        navHostController: NavHostController,
        keyboardController: SoftwareKeyboardController?
){
        val viewStates = loginModel.viewStates
        Box(
                modifier = Modifier.fillMaxSize()
        ) {
                //背景图
                Image(
                        painter = painterResource(R.mipmap.login_bg),
                        contentDescription = null,
                        modifier = Modifier.fillMaxSize(),
                        contentScale = ContentScale.FillBounds
                )

                LazyColumn(
                        modifier = Modifier.fillMaxSize().pointerInput(UInt){
                                detectTapGestures(
                                        onPress = {
                                                keyboardController?.hide()
                                        }
                                )
                        },
                        horizontalAlignment = Alignment.CenterHorizontally
                ) {
                        item {
                                BackAndFinPassWordComposable(){
                                        keyboardController?.hide()
                                        //关闭页面
                                        navHostController.navigateUp()
                                }

                                Image(
                                        modifier = Modifier
                                                .padding(top = 50.dp)
                                                .size(100.dp)
                                                .align(Alignment.Center),
                                        painter = painterResource(R.mipmap.ic_account),
                                        contentDescription = null
                                )

                                UserNameAndPasswordComposable(loginModel)

                                LoginBtnAndTextComposable(
                                        navHostController=navHostController,
                                        loginModel,
                                        loginClick = {
                                                keyboardController?.hide()
                                                loginModel.dispatch(LoginViewAction.Login)
//                                                if (viewStates.isReg){
//                                                        loginModel.dispatch(LoginViewAction.Reg)
//                                                }
//                                                else{
//                                                        loginModel.dispatch(LoginViewAction.Login)
//                                                }
                                        },
                                        registerClick = {
                                                //loginModel.dispatch(LoginViewAction.UpdateIsReg(!viewStates.isReg))
                                                //loginModel.getUserLoginData()
                                                mainViewModel.toBuyUrl.value = loginModel.getRegUrl()

                                        }
                                )
                        }
                }
        }
}

/**
 * 用户名和密码
 */

@Composable
fun UserNameAndPasswordComposable(
        loginModel : LoginAndRegViewModel,
) {


        val userNameModifier = Modifier
                .padding(start = 50.dp, end = 50.dp, top = 50.dp)
                .fillMaxWidth()
                .height(56.dp)

        val passWordModifier =
                Modifier
                        .padding(start = 50.dp, end = 50.dp, top = 20.dp)
                        .fillMaxWidth()
                        .height(56.dp)
        //用户名
        OutlinedTextField(
                loginModel.viewStates.userName,
                onValueChange = { newValue ->
                   loginModel.dispatch(LoginViewAction.UpdateAccount(newValue))
                },
                label = {
                        Text("邮箱地址", fontSize = 13.sp)
                },
                leadingIcon = {
                        Icon(
                                painterResource(R.drawable.account_circle),
                                contentDescription = null
                        )
                },
                colors = TextFieldDefaults.textFieldColors(
                        unfocusedLabelColor = Color.White,
                        textColor = Color.White,
                        backgroundColor = Color.Transparent,
                        focusedLabelColor = Color.White,
                        leadingIconColor = Color.White,
                        focusedIndicatorColor = Color.White,
                        unfocusedIndicatorColor = Color.White,
                        //光标
                        cursorColor = Color.White
                ),
                singleLine = true,
                modifier = userNameModifier,
                textStyle = TextStyle(
                        fontSize = 13.sp
                )
        )


        //密码
        OutlinedTextField(
                loginModel.viewStates.passWord,
                onValueChange = { newValue ->
                        loginModel.dispatch(LoginViewAction.UpdatePassword(newValue))
                },
                label = {
                        Text("请输入密码", fontSize = 13.sp)
                },
                leadingIcon = {
                        Icon(
                                painterResource(R.drawable.lock),
                                contentDescription = null
                        )
                },
                trailingIcon = {
                        IconButton(onClick = {

                                loginModel.dispatch(LoginViewAction.UpdateButtonVisible(!loginModel.viewStates.loginButtonVisible))
                        }) {
                                Icon(
                                        painter = if (loginModel.viewStates.loginButtonVisible) painterResource(R.drawable.visibility) else painterResource(
                                                R.drawable.visibility_off
                                        ), contentDescription = null,
                                        modifier = Modifier.size(20.dp),
                                        tint = Color.White
                                )
                        }
                },
                colors = TextFieldDefaults.textFieldColors(
                        unfocusedLabelColor = Color.White,
                        textColor = Color.White,
                        backgroundColor = Color.Transparent,
                        focusedLabelColor = Color.White,
                        leadingIconColor = Color.White,
                        focusedIndicatorColor = Color.White,
                        unfocusedIndicatorColor = Color.White,
                        //光标
                        cursorColor = Color.White
                ),
                singleLine = true,
                modifier = passWordModifier,
                textStyle = TextStyle(
                        fontSize = 13.sp
                ),
                //输入类型设置为密码
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                //转化为不可见的密码
                visualTransformation = if (!loginModel.viewStates.loginButtonVisible) PasswordVisualTransformation() else VisualTransformation.None
        )
}

/**
 * 返回上个页面和跳过
 */
@Composable
fun BackAndFinPassWordComposable(
        back: () -> Unit,
) {
        Row(
                modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 40.dp),
                //第一个和最后一个按钮分别靠左边界和右边界
                horizontalArrangement = Arrangement.SpaceBetween
        ) {
                Icon(
                        imageVector=Icons.Default.Close,
                        contentDescription = null,
                        modifier = Modifier
                                .clickable(onClick = back)
                                .padding(10.dp),
                        tint = Color.White
                )

//                Text(
//                        text = "跳过",
//                        fontSize = 13.sp,
//                        color = Color.White,
//                        modifier = Modifier.padding(10.dp)
//                )
        }
}


/**
 * 登录按钮
 * 用户注册 作者登录
 */
@Composable
private fun LoginBtnAndTextComposable(
        navHostController: NavHostController,
        loginModel: LoginAndRegViewModel,
        loginClick: () -> Unit,
        registerClick: () -> Unit
) {
        val viewStates = loginModel.viewStates

        //登录
        Button(
                onClick = loginClick,
                modifier = Modifier
                        .padding(start = 50.dp, end = 50.dp, top = 30.dp)
                        .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(
                        //透明的背景
                        backgroundColor = c_B3F,
                        contentColor = Color.Black
                )
        ) {

                when (viewStates.pageState) {
                        is PageState.Loading -> {
                                CircularProgressIndicator(
                                        color = MaterialTheme.colors.primary,
                                        modifier = Modifier
                                                .padding(5.dp)
                                                .width(20.dp)
                                                .height(20.dp)
                                )
                        }
                        is PageState.LoadingDialog -> DialogBoxLoading()
                        is PageState.Error -> {
                                SimpleAlertDialog(
                                        "提示",
                                        viewStates.pageState.exception,
                                        confirmStr = "重新尝试",
                                        confirmClick = {
                                            loginModel.dispatch(LoginViewAction.Login)
                                        }
                                ){
                                  loginModel.dispatch(LoginViewAction.UpdatePageState(PageState.NoLoading))
                                }
                        }
                        is PageState.Success -> {
                                navHostController.navigateUp()
                           //Text("登录完成", fontSize = 14.sp)
                        }
                        else -> {
                                Text("登录", fontSize = 14.sp)
                        }
                }

        }


        //注册
        Button(
                onClick = registerClick,
                modifier = Modifier
                        .padding(start = 50.dp, end = 50.dp, top = 10.dp)
                        .fillMaxWidth(),
                colors = ButtonDefaults.buttonColors(
                        //透明的背景
                        backgroundColor = c_B3F,
                        contentColor = Color.Black
                )
        ) {
                Text("注册", fontSize = 14.sp)
        }

//        if (!loginModel.loginButtonVisible.value){
//
//                //注册
//                Button(
//                        onClick = registerClick,
//                        modifier = Modifier
//                                .padding(start = 50.dp, end = 50.dp, top = 10.dp)
//                                .fillMaxWidth(),
//                        colors = ButtonDefaults.buttonColors(
//                                //透明的背景
//                                backgroundColor = c_B3F,
//                                contentColor = Color.Black
//                        )
//                ) {
//                        Text("用户注册", fontSize = 14.sp)
//                }
//        } else {
////                Button(
////                       onClick={
////                            loginModel.loginButtonVisible.value = false
////                       },
////                        modifier = Modifier
////                        .padding(start = 50.dp, end = 50.dp, top = 10.dp)
////                ){
////                        Text( text = "返回登录")
////                }
//

//        }


}