package com.example.maposition

import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
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 EditGroupActivity : AppCompatActivity() {

    companion object {
        const val EXTRA_GROUP = "group_name"
    }

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

    private var originalName: String? = null
    private val recipients = mutableListOf<Recipient>()

    private lateinit var recipientsList: LinearLayout
    private lateinit var nameLayout: TextInputLayout
    private lateinit var nameInput: TextInputEditText

    private val pickContact =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode != RESULT_OK) return@registerForActivityResult
            val uri = result.data?.data ?: return@registerForActivityResult
            contentResolver.query(
                uri,
                arrayOf(
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                ),
                null, null, null
            )?.use { c ->
                if (c.moveToFirst()) {
                    val name = c.getString(0) ?: ""
                    val phone = (c.getString(1) ?: "").replace(" ", "")
                    if (phone.isBlank()) {
                        Toast.makeText(this, R.string.error_contact_no_phone, Toast.LENGTH_SHORT).show()
                    } else {
                        addRecipient(Recipient(name, phone))
                    }
                }
            }
        }

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

        recipientsList = findViewById(R.id.recipientsList)
        nameLayout = findViewById(R.id.groupNameLayout)
        nameInput = findViewById(R.id.groupNameInput)

        originalName = intent.getStringExtra(EXTRA_GROUP)
        val editing = originalName != null

        findViewById<TextView>(R.id.editTitle).setText(
            if (editing) R.string.group_edit else R.string.group_new
        )

        if (editing) {
            Prefs.getGroups(this).find { it.name == originalName }?.let { g ->
                nameInput.setText(g.name)
                recipients.addAll(g.recipients)
            }
        }

        findViewById<ImageButton>(R.id.backButton).setOnClickListener { finish() }
        findViewById<MaterialButton>(R.id.pickContactButton).setOnClickListener {
            pickContact.launch(
                Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
            )
        }
        findViewById<MaterialButton>(R.id.addManualButton).setOnClickListener {
            showRecipientDialog(null)
        }
        findViewById<MaterialButton>(R.id.saveGroupButton).setOnClickListener { saveGroup() }

        val deleteButton = findViewById<MaterialButton>(R.id.deleteGroupButton)
        if (editing) {
            deleteButton.setOnClickListener { confirmDelete() }
        } else {
            deleteButton.visibility = android.view.View.GONE
        }

        renderRecipients()
    }

    // --- Liste des destinataires ---

    private fun addRecipient(r: Recipient) {
        if (recipients.any { it.phone == r.phone }) {
            Toast.makeText(this, R.string.error_dup_phone, Toast.LENGTH_SHORT).show()
            return
        }
        recipients.add(r)
        renderRecipients()
    }

    private fun renderRecipients() {
        recipientsList.removeAllViews()
        if (recipients.isEmpty()) {
            val empty = TextView(this).apply {
                text = getString(R.string.no_recipients_yet)
                setPadding(8, 16, 8, 16)
            }
            recipientsList.addView(empty)
            return
        }
        recipients.forEachIndexed { index, r ->
            val item = layoutInflater.inflate(R.layout.item_recipient, recipientsList, false)
            item.findViewById<TextView>(R.id.recipientName).text = r.name.ifBlank { getString(R.string.unnamed_recipient) }
            item.findViewById<TextView>(R.id.recipientPhone).text = r.phone
            item.findViewById<ImageButton>(R.id.removeButton).setOnClickListener {
                recipients.removeAt(index)
                renderRecipients()
            }
            item.setOnClickListener { showRecipientDialog(index) }
            recipientsList.addView(item)
        }
    }

    private fun showRecipientDialog(index: Int?) {
        val existing = index?.let { recipients[it] }
        val view = layoutInflater.inflate(R.layout.dialog_recipient, null)
        val rNameInput = view.findViewById<TextInputEditText>(R.id.recipientNameInput)
        val rPhoneLayout = view.findViewById<TextInputLayout>(R.id.recipientPhoneLayout)
        val rPhoneInput = view.findViewById<TextInputEditText>(R.id.recipientPhoneInput)

        if (existing != null) {
            rNameInput.setText(existing.name)
            rPhoneInput.setText(existing.phone)
        }

        val dialog = MaterialAlertDialogBuilder(this)
            .setTitle(if (existing == null) R.string.recipient_new else R.string.recipient_edit)
            .setView(view)
            .setPositiveButton(R.string.save, null)
            .setNegativeButton(android.R.string.cancel, null)
            .create()

        dialog.setOnShowListener {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
                val name = rNameInput.text.toString().trim()
                val phone = rPhoneInput.text.toString().trim()
                rPhoneLayout.error = null
                when {
                    phone.isEmpty() || !phoneRegex.matches(phone) ->
                        rPhoneLayout.error = getString(R.string.error_bad_phone, phone)
                    recipients.anyIndexed(index) { it.phone == phone } ->
                        rPhoneLayout.error = getString(R.string.error_dup_phone)
                    else -> {
                        val r = Recipient(name, phone)
                        if (index != null) recipients[index] = r else recipients.add(r)
                        renderRecipients()
                        dialog.dismiss()
                    }
                }
            }
        }
        dialog.show()
    }

    /** any() en ignorant l'élément en cours d'édition. */
    private fun List<Recipient>.anyIndexed(skip: Int?, pred: (Recipient) -> Boolean): Boolean =
        filterIndexed { i, _ -> i != skip }.any(pred)

    // --- Enregistrement / suppression du groupe ---

    private fun saveGroup() {
        val name = nameInput.text.toString().trim()
        nameLayout.error = null

        val groups = Prefs.getGroups(this)
        when {
            name.isEmpty() -> {
                nameLayout.error = getString(R.string.error_no_group_name)
                return
            }
            groups.any { it.name == name && it.name != originalName } -> {
                nameLayout.error = getString(R.string.error_dup_group)
                return
            }
            recipients.isEmpty() -> {
                Toast.makeText(this, R.string.error_no_recipients, Toast.LENGTH_SHORT).show()
                return
            }
        }

        val idx = groups.indexOfFirst { it.name == originalName }
        val group = Group(name, recipients.toList())
        if (idx >= 0) groups[idx] = group else groups.add(group)
        Prefs.saveGroups(this, groups)
        if (originalName != null && Prefs.getActiveGroupName(this) == originalName) {
            Prefs.setActiveGroupName(this, name)
        }
        finish()
    }

    private fun confirmDelete() {
        MaterialAlertDialogBuilder(this)
            .setMessage(getString(R.string.delete_group_confirm, originalName))
            .setPositiveButton(R.string.delete) { _, _ ->
                val groups = Prefs.getGroups(this)
                groups.removeAll { it.name == originalName }
                Prefs.saveGroups(this, groups)
                finish()
            }
            .setNegativeButton(android.R.string.cancel, null)
            .show()
    }
}
