package com.sambath.kunkhmer.screen.register

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Html
import android.view.MenuItem
import android.view.View
import android.widget.ArrayAdapter
import android.widget.TextView
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.screen.login.LoginActivity
import kotlinx.android.synthetic.main.activity_register.et_gender
import kotlinx.android.synthetic.main.activity_register.radioGroup
import kotlinx.android.synthetic.main.activity_register.til_email
import kotlinx.android.synthetic.main.activity_register.til_phone

class RegisterActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val spinnerData = listOf("Select Gender", "Female", "Male", "Other")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerData)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        et_gender.adapter = adapter
        et_gender.setSelection(0)

        setGender()

        val textView = findViewById<TextView>(R.id.tv_agreement)
        textView.text = Html.fromHtml(getString(R.string.agreement_hint))
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                onBackPressed() // Navigate back when the back button (up button) is pressed
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()

        // Start the LoginActivity
        val intent = Intent(this, LoginActivity::class.java)
        startActivity(intent)

        // Finish the RegisterActivity to prevent it from going back to the RegisterActivity
        finish()
    }

    private fun setGender() {
        if (radioGroup.checkedRadioButtonId == R.id.radioButtonEmail) {
            til_email.visibility = View.VISIBLE
            til_phone.visibility = View.GONE
        } else if (radioGroup.checkedRadioButtonId == R.id.radioButtonPhone) {
            til_email.visibility = View.GONE
            til_phone.visibility = View.VISIBLE
        }

        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.radioButtonEmail -> {
                    til_email.visibility = View.VISIBLE
                    til_phone.visibility = View.GONE
                }
                R.id.radioButtonPhone -> {
                    til_email.visibility = View.GONE
                    til_phone.visibility = View.VISIBLE
                }
            }
        }
    }
}