package com.example.maposition

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
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}$""")
    private lateinit var groupsList: LinearLayout

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

        groupsList = findViewById(R.id.groupsList)

        val nameInput = findViewById<TextInputEditText>(R.id.nameInput)
        nameInput.setText(Prefs.getName(this))
        nameInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
            override fun onTextChanged(s: CharSequence?, a: Int, b: Int, c: Int) {}
            override fun afterTextChanged(s: Editable?) {
                Prefs.setName(this@SettingsActivity, s?.toString() ?: "")
            }
        })

        findViewById<ImageButton>(R.id.backButton).setOnClickListener { finish() }
        findViewById<MaterialButton>(R.id.addGroupButton).setOnClickListener { showGroupDialog(null) }

        renderGroups()
    }

    private fun renderGroups() {
        groupsList.removeAllViews()
        val groups = Prefs.getGroups(this)

        if (groups.isEmpty()) {
            val empty = TextView(this).apply {
                text = getString(R.string.no_groups)
                setPadding(8, 24, 8, 24)
            }
            groupsList.addView(empty)
            return
        }

        val activeName = Prefs.getActiveGroup(this)?.name
        groups.forEach { g ->
            val item = layoutInflater.inflate(R.layout.item_group, groupsList, false)
            val title = if (g.name == activeName) {
                getString(R.string.group_active_suffix, g.name)
            } else {
                g.name
            }
            item.findViewById<TextView>(R.id.groupName).text = title
            item.findViewById<TextView>(R.id.groupPhones).text = g.phones.joinToString(", ")
            item.setOnClickListener { showGroupDialog(g) }
            groupsList.addView(item)
        }
    }

    private fun showGroupDialog(existing: Group?) {
        val view = layoutInflater.inflate(R.layout.dialog_group, null)
        val nameLayout = view.findViewById<TextInputLayout>(R.id.groupNameLayout)
        val nameInput = view.findViewById<TextInputEditText>(R.id.groupNameInput)
        val phonesLayout = view.findViewById<TextInputLayout>(R.id.groupPhonesLayout)
        val phonesInput = view.findViewById<TextInputEditText>(R.id.groupPhonesInput)

        if (existing != null) {
            nameInput.setText(existing.name)
            phonesInput.setText(existing.phones.joinToString(";"))
        }

        val builder = MaterialAlertDialogBuilder(this)
            .setTitle(if (existing == null) R.string.group_new else R.string.group_edit)
            .setView(view)
            .setPositiveButton(R.string.save, null)
            .setNegativeButton(android.R.string.cancel, null)
        if (existing != null) builder.setNeutralButton(R.string.delete, null)

        val dialog = builder.create()
        dialog.setOnShowListener {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
                val name = nameInput.text.toString().trim()
                val phones = phonesInput.text.toString()
                    .split(";").map { it.trim() }.filter { it.isNotEmpty() }
                nameLayout.error = null
                phonesLayout.error = null

                val groups = Prefs.getGroups(this)
                when {
                    name.isEmpty() ->
                        nameLayout.error = getString(R.string.error_no_group_name)
                    groups.any { it.name == name && it.name != existing?.name } ->
                        nameLayout.error = getString(R.string.error_dup_group)
                    phones.isEmpty() ->
                        phonesLayout.error = getString(R.string.error_no_phone)
                    phones.any { !phoneRegex.matches(it) } ->
                        phonesLayout.error = getString(
                            R.string.error_bad_phone,
                            phones.first { !phoneRegex.matches(it) }
                        )
                    else -> {
                        val idx = groups.indexOfFirst { it.name == existing?.name }
                        if (idx >= 0) groups[idx] = Group(name, phones)
                        else groups.add(Group(name, phones))
                        Prefs.saveGroups(this, groups)
                        if (existing != null && Prefs.getActiveGroupName(this) == existing.name) {
                            Prefs.setActiveGroupName(this, name)
                        }
                        renderGroups()
                        dialog.dismiss()
                    }
                }
            }
            if (existing != null) {
                dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
                    val groups = Prefs.getGroups(this)
                    groups.removeAll { it.name == existing.name }
                    Prefs.saveGroups(this, groups)
                    renderGroups()
                    dialog.dismiss()
                }
            }
        }
        dialog.show()
    }
}
