package com.example.projekta

import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.util.Patterns
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.projekta.databinding.ActivityLoginBinding
import org.json.JSONObject

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding
    private var isPasswordVisible = false

    private val url = "http://192.168.43.191/projekta/login.php"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // =========================
        // CEK SESSION LOGIN
        // =========================
        val sharedPref = getSharedPreferences("LOGIN", MODE_PRIVATE)

        if (sharedPref.getBoolean("isLogin", false)) {
            startActivity(Intent(this, MenuActivity::class.java))
            finish()
        }

        binding.btnBack.setOnClickListener {
            finish()
        }

        setupPasswordToggle()

        binding.btnLogin.setOnClickListener {

            val email = binding.etEmail.text.toString().trim()
            val password = binding.etPassword.text.toString()

            // VALIDASI EMAIL
            if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                binding.etEmail.error = "Email tidak valid"
                return@setOnClickListener
            }

            // VALIDASI PASSWORD
            if (password.length < 6) {
                binding.etPassword.error = "Password minimal 6 karakter"
                return@setOnClickListener
            }

            loginUser(email, password)
        }

        binding.txtRegister.setOnClickListener {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }

    // =========================
    // LOGIN USER
    // =========================
    private fun loginUser(email: String, password: String) {

        val request = object : StringRequest(
            Request.Method.POST,
            url,

            { response ->

                try {

                    val json = JSONObject(response)

                    if (json.getString("status") == "success") {

                        val idUser = json.getString("id")
                        val nama = json.getString("nama")
                        val emailUser = json.getString("email")

                        // SIMPAN SESSION LOGIN
                        val sharedPref = getSharedPreferences("LOGIN", MODE_PRIVATE)

                        sharedPref.edit()
                            .putBoolean("isLogin", true)
                            .putString("id_user", idUser)
                            .putString("nama", nama)
                            .putString("email", emailUser)
                            .apply()

                        Toast.makeText(
                            this,
                            "Login berhasil",
                            Toast.LENGTH_SHORT
                        ).show()

                        startActivity(Intent(this, MenuActivity::class.java))
                        finish()

                    } else {

                        Toast.makeText(
                            this,
                            "Email / Password salah",
                            Toast.LENGTH_SHORT
                        ).show()

                    }

                } catch (e: Exception) {

                    Toast.makeText(
                        this,
                        "Response server tidak valid",
                        Toast.LENGTH_LONG
                    ).show()

                    e.printStackTrace()
                }

            },

            {

                Toast.makeText(
                    this,
                    "Gagal koneksi server",
                    Toast.LENGTH_LONG
                ).show()

            }

        ) {

            override fun getParams(): MutableMap<String, String> {

                val params = HashMap<String, String>()

                params["email"] = email
                params["password"] = password

                return params
            }

        }

        Volley.newRequestQueue(this).add(request)

    }

    // =========================
    // PASSWORD TOGGLE
    // =========================
    private fun setupPasswordToggle() {

        binding.etPassword.setOnTouchListener { _, event ->

            val drawableEnd = 2

            if (event.action == MotionEvent.ACTION_UP) {

                val drawable = binding.etPassword.compoundDrawables[drawableEnd]

                if (drawable != null &&
                    event.rawX >= (binding.etPassword.right - drawable.bounds.width())
                ) {

                    isPasswordVisible = !isPasswordVisible

                    if (isPasswordVisible) {

                        binding.etPassword.inputType =
                            InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

                        binding.etPassword.setCompoundDrawablesWithIntrinsicBounds(
                            R.drawable.ic_lock,
                            0,
                            R.drawable.ic_eye_off,
                            0
                        )

                    } else {

                        binding.etPassword.inputType =
                            InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

                        binding.etPassword.setCompoundDrawablesWithIntrinsicBounds(
                            R.drawable.ic_lock,
                            0,
                            R.drawable.ic_eye,
                            0
                        )

                    }

                    binding.etPassword.setSelection(binding.etPassword.text.length)

                    return@setOnTouchListener true
                }

            }

            false
        }
    }
}