package com.jihe.punchnet.screen

import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
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.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.jihe.punchnet.R
import com.jihe.punchnet.api.ApiClient
import com.jihe.punchnet.api.AuthLoginRequest
import com.jihe.punchnet.api.AuthTokenRequest
import com.jihe.punchnet.helper.PreferenceName
import com.jihe.punchnet.helper.setPreferenceString
import com.jihe.punchnet.sdlan.utils.UniqueNodeID
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@Composable
fun LoginScreen(navController: NavHostController) {
    var selectedTabIndex by remember { mutableStateOf(0) }
    val tabs = listOf("账号密码登录", "Token直连")

    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var token by remember { mutableStateOf("") }
    
    var isLoading by remember { mutableStateOf(false) }

    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current
    val apiClient = remember { ApiClient() }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Image(
            painter = painterResource(R.drawable.punchnet_log),
            contentDescription = "logo",
            modifier = Modifier.size(100.dp)
        )
        
        Spacer(modifier = Modifier.height(16.dp))

        Text(
            text = "Welcome to PunchNet",
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )

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

        TabRow(selectedTabIndex = selectedTabIndex) {
            tabs.forEachIndexed { index, title ->
                Tab(
                    selected = selectedTabIndex == index,
                    onClick = { selectedTabIndex = index },
                    text = { Text(title) }
                )
            }
        }

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

        if (selectedTabIndex == 0) {
            // Account Login
            OutlinedTextField(
                value = username,
                onValueChange = { username = it },
                label = { Text("用户名") },
                leadingIcon = { Icon(Icons.Default.Person, contentDescription = null) },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            Spacer(modifier = Modifier.height(16.dp))
            OutlinedTextField(
                value = password,
                onValueChange = { password = it },
                label = { Text("密码") },
                leadingIcon = { Icon(Icons.Default.Lock, contentDescription = null) },
                visualTransformation = PasswordVisualTransformation(),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
        } else {
            // Token Login
            OutlinedTextField(
                value = token,
                onValueChange = { token = it },
                label = { Text("连接 Token") },
                leadingIcon = { Icon(Icons.Default.Lock, contentDescription = null) },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
        }

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

        Button(
            onClick = {
                if (selectedTabIndex == 0 && (username.isEmpty() || password.isEmpty())) {
                    Toast.makeText(context, "请输入用户名和密码", Toast.LENGTH_SHORT).show()
                    return@Button
                }
                if (selectedTabIndex == 1 && token.isEmpty()) {
                    Toast.makeText(context, "请输入Token", Toast.LENGTH_SHORT).show()
                    return@Button
                }

                isLoading = true
                coroutineScope.launch {
                    UniqueNodeID.setBaseDir(context.filesDir.absolutePath)
                    val clientId = "punchnet_android_client_" + UniqueNodeID.getUUID(context)

                    try {
                        val response = if (selectedTabIndex == 0) {
                            val request = AuthLoginRequest(
                                clientId = clientId,
                                username = username,
                                password = password,
                                version = "1.0.0",
                                system = "Android " + android.os.Build.VERSION.RELEASE,
                                hostname = android.os.Build.MODEL
                            )
                            ApiClient().loginWithAccount(request)
                        } else {
                            val request = AuthTokenRequest(
                                clientId = clientId,
                                token = token,
                                version = "1.0.0",
                                system = "Android " + android.os.Build.VERSION.RELEASE,
                                hostname = android.os.Build.MODEL
                            )
                            ApiClient().loginWithToken(request)
                        }

                        withContext(Dispatchers.Main) {
                            isLoading = false
                            if (response != null && response.code == 0 && response.data != null) {
                                // Success! Save auth data as JSON and navigate
                                val authDataJson = com.google.gson.Gson().toJson(response.data)
                                setPreferenceString(context, PreferenceName.PreferenceToken, authDataJson)
                                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                                navController.navigate(Screen.MainScreen.route) {
                                    popUpTo(Screen.LoginScreen.route) { inclusive = true }
                                }
                            } else {
                                Toast.makeText(context, "登录失败: ${response?.message ?: "网络错误"}", Toast.LENGTH_LONG).show()
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        withContext(Dispatchers.Main) {
                            isLoading = false
                            Toast.makeText(context, "登录异常: ${e.message}", Toast.LENGTH_LONG).show()
                        }
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            shape = RoundedCornerShape(8.dp),
            enabled = !isLoading
        ) {
            if (isLoading) {
                CircularProgressIndicator(
                    modifier = Modifier.size(24.dp),
                    color = MaterialTheme.colorScheme.onPrimary,
                    strokeWidth = 2.dp
                )
            } else {
                Text("登录", fontSize = 16.sp)
            }
        }

        Spacer(modifier = Modifier.height(16.dp))
        
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Center
        ) {
            TextButton(
                onClick = {
                    Toast.makeText(context, "请前往官网注册账号", Toast.LENGTH_SHORT).show()
                }
            ) {
                Text("没有账号？去注册")
            }
        }
    }
}
