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.ActivityRegisterBinding

class RegisterActivity : AppCompatActivity() {

    private lateinit var binding: ActivityRegisterBinding

    private var isPasswordVisible = false
    private var isConfirmPasswordVisible = false

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

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

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

        binding.btnBack.setOnClickListener {
            finish()
        }

        setupPasswordToggle()

        binding.btnRegister.setOnClickListener {

            val name = binding.etName.text.toString().trim()
            val email = binding.etEmail.text.toString().trim()
            val password = binding.etPassword.text.toString()
            val confirmPassword = binding.etConfirmPassword.text.toString()

            // VALIDASI
            if (name.isEmpty()) {
                binding.etName.error = "Nama wajib diisi"
                return@setOnClickListener
            }

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

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

            if (password != confirmPassword) {
                binding.etConfirmPassword.error = "Password tidak sama"
                return@setOnClickListener
            }

            registerUser(name, email, password)
        }

        binding.txtLogin.setOnClickListener {
            finish()
        }
    }

    private fun registerUser(nama: String, email: String, password: String) {

        val request = object : StringRequest(
            Request.Method.POST,
            url,
            { response ->

                if (response.trim() == "success") {

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

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

                } else {
                    Toast.makeText(this, "Gagal: $response", Toast.LENGTH_LONG).show()
                }

            },
            {
                Toast.makeText(this, "Error koneksi server", Toast.LENGTH_LONG).show()
            }

        ) {

            override fun getParams(): MutableMap<String, String> {
                val params = HashMap<String, String>()

                // 🔥 INI YANG BENAR (HARUS SAMA DENGAN PHP)
                params["nama"] = nama
                params["email"] = email
                params["password"] = password

                return params
            }
        }

        Volley.newRequestQueue(this).add(request)
    }

    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
        }

        binding.etConfirmPassword.setOnTouchListener { _, event ->

            val drawableEnd = 2

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

                val drawable = binding.etConfirmPassword.compoundDrawables[drawableEnd]

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

                    isConfirmPasswordVisible = !isConfirmPasswordVisible

                    if (isConfirmPasswordVisible) {
                        binding.etConfirmPassword.inputType =
                            InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

                        binding.etConfirmPassword.setCompoundDrawablesWithIntrinsicBounds(
                            R.drawable.ic_lock,
                            0,
                            R.drawable.ic_eye_off,
                            0
                        )
                    } else {
                        binding.etConfirmPassword.inputType =
                            InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

                        binding.etConfirmPassword.setCompoundDrawablesWithIntrinsicBounds(
                            R.drawable.ic_lock,
                            0,
                            R.drawable.ic_eye,
                            0
                        )
                    }

                    binding.etConfirmPassword.setSelection(binding.etConfirmPassword.text.length)
                    return@setOnTouchListener true
                }
            }
            false
        }
    }
}