package com.example.maposition

import android.content.Context
import android.os.Bundle
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout

class SettingsActivity : AppCompatActivity() {

    private val phoneRegex = Regex("""^\+?[0-9][0-9 .\-]{5,16}$""")

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

        val prefs = getSharedPreferences("MaPositionPrefs", Context.MODE_PRIVATE)

        val nameInput = findViewById<TextInputEditText>(R.id.nameInput)
        val phonesLayout = findViewById<TextInputLayout>(R.id.phonesLayout)
        val phonesInput = findViewById<TextInputEditText>(R.id.phonesInput)

        nameInput.setText(prefs.getString("name", ""))
        phonesInput.setText(prefs.getString("phones", ""))

        findViewById<ImageButton>(R.id.backButton).setOnClickListener { finish() }

        findViewById<MaterialButton>(R.id.saveButton).setOnClickListener {
            val rawPhones = phonesInput.text.toString()
            val phones = rawPhones.split(";").map { it.trim() }.filter { it.isNotEmpty() }

            when {
                phones.isEmpty() -> {
                    phonesLayout.error = getString(R.string.error_no_phone)
                    return@setOnClickListener
                }
                phones.any { !phoneRegex.matches(it) } -> {
                    val bad = phones.first { !phoneRegex.matches(it) }
                    phonesLayout.error = getString(R.string.error_bad_phone, bad)
                    return@setOnClickListener
                }
            }
            phonesLayout.error = null

            prefs.edit()
                .putString("name", nameInput.text.toString().trim())
                .putString("phones", phones.joinToString(";"))
                .apply()

            Toast.makeText(this, getString(R.string.saved), Toast.LENGTH_SHORT).show()
            finish()
        }
    }
}
