package com.seyalix.hr.ui.auth

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.seyalix.hr.R
import com.seyalix.hr.api.ApiClient
import com.seyalix.hr.ui.MainActivity
import com.seyalix.hr.utils.PrefsManager
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException

class LoginActivity : AppCompatActivity() {

    private lateinit var prefs: PrefsManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        com.seyalix.hr.api.ApiClient.init(applicationContext)
        prefs = PrefsManager(this)

        // Skip login if already logged in
        if (prefs.isLoggedIn()) {
            startMain(); return
        }

        setContentView(R.layout.activity_login)

        val etUsername = findViewById<EditText>(R.id.etUsername)
        val etPassword = findViewById<EditText>(R.id.etPassword)
        val btnLogin   = findViewById<Button>(R.id.btnLogin)
        val progress   = findViewById<ProgressBar>(R.id.progressLogin)
        val tvError    = findViewById<TextView>(R.id.tvError)

        btnLogin.setOnClickListener {
            val username = etUsername.text.toString().trim()
            val password = etPassword.text.toString()
            if (username.isEmpty() || password.isEmpty()) {
                tvError.text = "Enter username and password"; tvError.visibility = View.VISIBLE; return@setOnClickListener
            }
            tvError.visibility = View.GONE
            btnLogin.isEnabled = false
            progress.visibility = View.VISIBLE

            lifecycleScope.launch {
                try {
                    val resp = ApiClient.apiService.login(mapOf("username" to username, "password" to password))
                    if (resp.isSuccessful && resp.body()?.success == true) {
                        val d = resp.body()!!.data!!
                        prefs.saveLogin(d.token, d.employeeId, d.name, d.role, d.empCode, d.photo)
                        startMain()
                    } else {
                        tvError.text = resp.body()?.message ?: "Login failed"
                        tvError.visibility = View.VISIBLE
                    }
                } catch (e: CancellationException) {
                    throw e  // normal when the screen changes mid-request — not a real error
                } catch (e: Exception) {
                    tvError.text = "Network error: ${e.message}"
                    tvError.visibility = View.VISIBLE
                } finally {
                    btnLogin.isEnabled = true
                    progress.visibility = View.GONE
                }
            }
        }
    }

    private fun startMain() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }
}
