// ui/login/LoginScreen.kt
package com.example.initiateaphonecallapp.ui.login

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.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.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(
    viewModel: LoginViewModel = viewModel(),
    onLoginSuccess: (String) -> Unit = {}
) {
    val loginState by viewModel.loginState.collectAsState()
    val autoLoginState by viewModel.autoLoginState.collectAsState()
    val rememberMe by viewModel.rememberMe.collectAsState()
    val autoLogin by viewModel.autoLogin.collectAsState()

    // 监听登录成功状态
    LaunchedEffect(loginState.isLoginSuccess) {
        if (loginState.isLoginSuccess && loginState.authToken != null) {
            onLoginSuccess(loginState.authToken!!)
        }
    }

    // 显示自动登录状态
    if (autoLoginState == LoginViewModel.AutoLoginState.CHECKING) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White),
            contentAlignment = Alignment.Center
        ) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                CircularProgressIndicator(
                    modifier = Modifier.size(50.dp),
                    color = Color(0xFF10A37F)
                )
                Spacer(modifier = Modifier.height(20.dp))
                Text(
                    text = "自动登录中...",
                    fontSize = 16.sp,
                    color = Color.Gray
                )
            }
        }
        return
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
            .padding(horizontal = 32.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier.fillMaxWidth()
        ) {
            // Logo/标题区域
            Icon(
                painter = painterResource(id = android.R.drawable.ic_dialog_email),
                contentDescription = "App Logo",
                modifier = Modifier.size(80.dp),
                tint = Color(0xFF10A37F)
            )

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

            // 标题
            Text(
                text = "登录您的账户",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Black,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )

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

            Text(
                text = "欢迎回来，请登录您的账户",
                fontSize = 14.sp,
                color = Color.Gray,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )

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

            // 用户名输入框
            OutlinedTextField(
                value = loginState.username,
                onValueChange = viewModel::onUsernameChange,
                label = { Text("账号") },
                placeholder = { Text("请输入您的账号") },
                singleLine = true,
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(12.dp)),
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = Color(0xFF10A37F),
                    unfocusedBorderColor = Color(0xFFE5E5E5),
                    focusedTextColor = Color.Black,
                    focusedPlaceholderColor = Color(0xFF999999),
                    unfocusedTextColor = Color.Black,
                    unfocusedPlaceholderColor = Color(0xFF999999)
                ),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
            )

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

            // 密码输入框
            OutlinedTextField(
                value = loginState.password,
                onValueChange = viewModel::onPasswordChange,
                label = { Text("密码") },
                placeholder = { Text("请输入您的密码") },
                singleLine = true,
                visualTransformation = PasswordVisualTransformation(),
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(12.dp)),
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = Color(0xFF10A37F),
                    unfocusedBorderColor = Color(0xFFE5E5E5),
                    focusedTextColor = Color.Black,
                    focusedPlaceholderColor = Color(0xFF999999),
                    unfocusedTextColor = Color.Black,
                    unfocusedPlaceholderColor = Color(0xFF999999)
                ),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
            )

            // 记住我和自动登录选项
            Spacer(modifier = Modifier.height(16.dp))
            Column(
                modifier = Modifier.fillMaxWidth()
            ) {
                // 记住我选项
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Checkbox(
                        checked = rememberMe,
                        onCheckedChange = viewModel::onRememberMeChange,
                        colors = CheckboxDefaults.colors(
                            checkedColor = Color(0xFF10A37F)
                        )
                    )
                    Text(
                        text = "记住密码",
                        fontSize = 14.sp,
                        color = Color.Black,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }

                // 自动登录选项
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Checkbox(
                        checked = autoLogin,
                        onCheckedChange = viewModel::onAutoLoginChange,
                        enabled = rememberMe,
                        colors = CheckboxDefaults.colors(
                            checkedColor = Color(0xFF10A37F)
                        )
                    )
                    Text(
                        text = "自动登录",
                        fontSize = 14.sp,
                        color = if (rememberMe) Color.Black else Color.Gray,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }

            // 错误信息显示
            if (loginState.errorMessage.isNotEmpty()) {
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = loginState.errorMessage,
                    color = Color.Red,
                    fontSize = 14.sp,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth()
                )
            }

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

            // 登录按钮
            Button(
                onClick = {
                    viewModel.login()
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(50.dp)
                    .clip(RoundedCornerShape(12.dp)),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF10A37F),
                    disabledContainerColor = Color(0xFFCCCCCC)
                ),
                enabled = !loginState.isLoading
            ) {
                if (loginState.isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = Color.White,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text(
                        text = "登录",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            }

            Spacer(modifier = Modifier.height(20.dp))
        }
    }
}