package com.b2lmobitech.fieldcloudhrms

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class LoginScreen : AppCompatActivity() {

    private lateinit var edtEmail: EditText
    private lateinit var edtPassword: EditText
    private lateinit var btnLogin: Button
    private lateinit var txtForgot: TextView

    private val PREF_NAME = "login_pref"
    private val KEY_EMAIL = "email"
    private val KEY_LOGGED_IN = "isLoggedIn"
    private val KEY_USERID = "user_id"
    private val KEY_ORGID = "org_id"
    private val KEY_NAME = "name"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login_screen)

        val sharedPref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

        // Check if already logged in
        if (sharedPref.getBoolean(KEY_LOGGED_IN, false)) {
            goToHome()
            return
        }

        edtEmail = findViewById(R.id.edtEmail)
        edtPassword = findViewById(R.id.edtPassword)
        btnLogin = findViewById(R.id.btnLogin)
//        txtForgot = findViewById(R.id.txtForgot)

        var isPasswordVisible = false

        edtPassword.setOnTouchListener { _, event ->
            if (event.action == android.view.MotionEvent.ACTION_UP) {

                // Detect click on drawableEnd
                if (event.rawX >= (edtPassword.right - edtPassword.compoundDrawables[2].bounds.width())) {

                    if (isPasswordVisible) {
                        // Hide password
                        edtPassword.inputType =
                            android.text.InputType.TYPE_CLASS_TEXT or
                                    android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
                        edtPassword.setCompoundDrawablesWithIntrinsicBounds(
                            0, 0, R.drawable.outline_key_24, 0
                        )
                    } else {
                        // Show password
                        edtPassword.inputType =
                            android.text.InputType.TYPE_CLASS_TEXT or
                                    android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                        edtPassword.setCompoundDrawablesWithIntrinsicBounds(
                            0, 0, R.drawable.outline_key_off_24, 0
                        )
                    }

                    edtPassword.setSelection(edtPassword.text.length)
                    isPasswordVisible = !isPasswordVisible
                    return@setOnTouchListener true
                }
            }
            false
        }


        btnLogin.setOnClickListener {
            val email = edtEmail.text.toString().trim()
            val password = edtPassword.text.toString().trim()

            if (email.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Please enter email and password", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val call = RetrofitClient.instance.login(email, password)

            call.enqueue(object : retrofit2.Callback<LoginResponse> {
                override fun onResponse(
                    call: retrofit2.Call<LoginResponse>,
                    response: retrofit2.Response<LoginResponse>
                ) {
                    Log.d("RAW_RESPONSE", response.raw().toString())
                    Log.d("FULL_BODY", response.body()?.toString() ?: "NULL BODY")
                    Log.d("ERROR_BODY", response.errorBody()?.string() ?: "NO ERROR BODY")
                    val res = response.body()
                    Log.d("res","$res");

                    if (res != null && res.status == "success") {

                        val editor = sharedPref.edit()
                        editor.putString(KEY_EMAIL, res.email ?: "")
                        editor.putString(KEY_USERID,res.user_id)
                        editor.putString(KEY_ORGID,res.org_id)
                        editor.putString(KEY_NAME, res.username)
                        editor.putBoolean(KEY_LOGGED_IN, true)
                        editor.apply()

                        Toast.makeText(this@LoginScreen, "Login successful", Toast.LENGTH_SHORT).show()
                        goToHome()

                    } else {
                        Toast.makeText(this@LoginScreen, "Invalid email or password", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: retrofit2.Call<LoginResponse>, t: Throwable) {
                    Toast.makeText(this@LoginScreen, "Error: ${t.message}", Toast.LENGTH_LONG).show()
                }
            })

        }


//        txtForgot.setOnClickListener {
//            Toast.makeText(this, "Forgot Password Clicked!", Toast.LENGTH_SHORT).show()
//        }
    }

    private fun goToHome() {
        startActivity(Intent(this, HomeActivity::class.java))
        finish()
    }
}
