package com.b2lmobitech.fieldcloudhrms

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class SettingsActivity : AppCompatActivity() {

    private lateinit var btnBack: ImageView
    private lateinit var txtProfileName: TextView
    private lateinit var txtEmail: TextView
    private lateinit var txtUserId: TextView
    private lateinit var layoutViewProfile: TextView
    private lateinit var txtSignOut: TextView
    private lateinit var imgLogout: ImageView

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

        btnBack = findViewById(R.id.btnBack)
        txtProfileName = findViewById(R.id.txtProfileName)
        txtEmail = findViewById(R.id.txtEmail)
        txtUserId = findViewById(R.id.txtUserId)
        layoutViewProfile = findViewById(R.id.btnViewProfile)
        txtSignOut = findViewById(R.id.txtSignOut)
        imgLogout = findViewById(R.id.imgLogout)

        val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
        val userId = sharedPref.getString("user_id", "") ?: ""
        val orgId = sharedPref.getString("org_id", "") ?: ""
        val name = sharedPref.getString("name", "") ?: ""
        val email = sharedPref.getString("email", "") ?: ""

        // Optional: load from SharedPreferences or API
        txtProfileName.text = name
        txtEmail.text = email
        txtUserId.text = "User ID: $userId"

        btnBack.setOnClickListener { finish() }

        layoutViewProfile.setOnClickListener {
            // open profile page
            startActivity(Intent(this, ViewProfileActivity::class.java))
        }

        imgLogout.setOnClickListener { logout() }
        txtSignOut.setOnClickListener { logout() }
    }

    private fun logout() {
        // TODO: clear saved session/token
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("Logout")
            .setMessage("Are you sure you want to log out?")
            .setCancelable(false)
            .setPositiveButton("Yes") { dialog, _ ->

                // Clear session
                val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
                sharedPref.edit().clear().apply()

                // Go to login screen
                startActivity(Intent(this, LoginScreen::class.java))
                finishAffinity()

                dialog.dismiss()
            }
            .setNegativeButton("No") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }
}
