package com.example.myapplication.ui.login

import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import android.widget.FrameLayout
import android.widget.TextView
import com.example.myapplication.R
import com.example.myapplication.network.ApiResponse
import com.example.myapplication.network.LoginRequest
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.utils.EncryptedSharedPreferencesUtil
import com.google.android.material.button.MaterialButton
import android.widget.Toast
import kotlinx.coroutines.launch

class LoginFragment : Fragment() {

    private lateinit var passwordEditText: EditText
    private lateinit var toggleImageView: ImageView
    private lateinit var loginButton: TextView 
    private lateinit var emailEditText: EditText
    private var loadingOverlay: com.example.myapplication.ui.common.LoadingOverlay? = null//加载遮罩层

    private var isPasswordVisible = false
    
    override fun onDestroyView() {
        loadingOverlay?.remove()
        loadingOverlay = null
        super.onDestroyView()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_login, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadingOverlay = com.example.myapplication.ui.common.LoadingOverlay.attach(view as ViewGroup)

         // 注册
        view.findViewById<TextView>(R.id.tv_signup).setOnClickListener {
             findNavController().navigate(R.id.action_mineFragment_to_registerFragment)
          }
        // 忘记密码
        view.findViewById<TextView>(R.id.tv_forgot_password).setOnClickListener {
             findNavController().navigate(R.id.action_loginFragment_to_forgetPasswordEmailFragment)
          }
        // 返回按钮
          view.findViewById<FrameLayout>(R.id.iv_close).setOnClickListener {
            findNavController().previousBackStackEntry
                ?.savedStateHandle
                ?.set("from_login", true)

            findNavController().popBackStack()
        }
        // 绑定控件（id 必须和 xml 里的一样）
        passwordEditText = view.findViewById(R.id.et_password)
        emailEditText = view.findViewById(R.id.et_email)
        toggleImageView = view.findViewById(R.id.iv_toggle)
        loginButton = view.findViewById(R.id.btn_login)

        // 账号回填
        val savedEmail = EncryptedSharedPreferencesUtil.get(requireContext(), "email", String::class.java)
        savedEmail?.let { email ->
            emailEditText.setText(email)
        }

        // 初始是隐藏密码状态
        passwordEditText.inputType =
            InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

        toggleImageView.setOnClickListener {
            isPasswordVisible = !isPasswordVisible

            if (isPasswordVisible) {
                // 显示密码
                passwordEditText.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                toggleImageView.setImageResource(R.drawable.display)
            } else {
                // 隐藏密码
                passwordEditText.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                toggleImageView.setImageResource(R.drawable.hide)
            }

            // 保持光标在末尾
            passwordEditText.setSelection(passwordEditText.text?.length ?: 0)
        }

        // // 登录按钮逻辑
        loginButton.setOnClickListener {
            val pwd = passwordEditText.text?.toString().orEmpty()
             val email = emailEditText.text?.toString().orEmpty()
            if (pwd.isEmpty() || email.isEmpty()) {
                // 输入框不能为空
                Toast.makeText(requireContext(), "The password and email address cannot be left empty!", Toast.LENGTH_SHORT).show()
            } else {
                loadingOverlay?.show()
                // 调用登录API
                lifecycleScope.launch {
                    try {
                        val loginRequest = LoginRequest(
                            mail = email,  // 使用email作为username
                            password = pwd
                        )
                        val response = RetrofitClient.apiService.login(loginRequest)
                        // 存储登录响应
                        if (response.code == 0) {
                        EncryptedSharedPreferencesUtil.save(requireContext(), "user", response.data)
                        EncryptedSharedPreferencesUtil.save(requireContext(), "email",email)
                        findNavController().popBackStack()
                        } else {
                            Toast.makeText(requireContext(), "Login failed: ${response.message}", Toast.LENGTH_SHORT).show()
                        }
                        loadingOverlay?.hide()
                    } catch (e: Exception) {
                        Log.e("1314520-LoginFragment", "登录请求失败: ${e.message}", e)
                        Toast.makeText(requireContext(), "Login failed: ${e.message}", Toast.LENGTH_SHORT).show()
                        loadingOverlay?.hide()
                    }
                }
            }
        }
    }
}
