package club.clubk.ktag.apps.mqttbroker

import android.os.Bundle
import android.text.InputType
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import club.clubk.ktag.apps.sharedservices.MqttPreferenceKeys

class BrokerSettingsFragment : PreferenceFragmentCompat() {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.broker_settings_pref, rootKey)

        findPreference<Preference>("broker_manage_users")?.setOnPreferenceClickListener {
            showManageUsersDialog()
            true
        }

        // Set up autodiscovery toggle to enable/disable manual connection fields
        val autodiscoveryPref = findPreference<SwitchPreferenceCompat>(MqttPreferenceKeys.AUTODISCOVERY)
        autodiscoveryPref?.setOnPreferenceChangeListener { _, newValue ->
            updateManualFieldsEnabled(newValue as Boolean)
            true
        }
        updateManualFieldsEnabled(autodiscoveryPref?.isChecked ?: false)

        updateManageUsersSummary()
    }

    private fun updateManualFieldsEnabled(autodiscoveryEnabled: Boolean) {
        val disabled = autodiscoveryEnabled
        findPreference<Preference>(MqttPreferenceKeys.SERVER_URI)?.isEnabled = !disabled
        findPreference<Preference>(MqttPreferenceKeys.USERNAME)?.isEnabled = !disabled
        findPreference<Preference>(MqttPreferenceKeys.PASSWORD)?.isEnabled = !disabled
    }

    private fun updateManageUsersSummary() {
        val count = CredentialManager.getCredentialCount(requireContext())
        findPreference<Preference>("broker_manage_users")?.summary =
            if (count == 0) "No users configured"
            else "$count user(s) configured"
    }

    private fun showManageUsersDialog() {
        val context = requireContext()
        val credentials = CredentialManager.loadCredentials(context)
        val usernames = credentials.keys.toList()

        val builder = AlertDialog.Builder(context)
            .setTitle("Manage Users")
            .setPositiveButton("Add User") { _, _ -> showAddUserDialog() }
            .setNegativeButton("Close", null)

        if (usernames.isEmpty()) {
            builder.setMessage("No users configured. Add a user to enable authentication.")
        } else {
            builder.setItems(usernames.toTypedArray()) { _, which ->
                showRemoveUserDialog(usernames[which])
            }
        }

        builder.show()
    }

    private fun showAddUserDialog() {
        val context = requireContext()

        val layout = LinearLayout(context).apply {
            orientation = LinearLayout.VERTICAL
            val pad = (16 * resources.displayMetrics.density).toInt()
            setPadding(pad, pad, pad, 0)
        }

        val usernameInput = EditText(context).apply {
            hint = "Username"
            inputType = InputType.TYPE_CLASS_TEXT
        }
        layout.addView(usernameInput)

        val passwordInput = EditText(context).apply {
            hint = "Password"
            inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }
        layout.addView(passwordInput)

        AlertDialog.Builder(context)
            .setTitle("Add User")
            .setView(layout)
            .setPositiveButton("Add") { _, _ ->
                val username = usernameInput.text.toString().trim()
                val password = passwordInput.text.toString()

                when {
                    username.isEmpty() || password.isEmpty() -> {
                        Toast.makeText(context, "Username and password are required", Toast.LENGTH_SHORT).show()
                    }
                    username.contains(":") -> {
                        Toast.makeText(context, "Username cannot contain ':'", Toast.LENGTH_SHORT).show()
                    }
                    else -> {
                        CredentialManager.addCredential(context, username, password)
                        Toast.makeText(context, "User '$username' added", Toast.LENGTH_SHORT).show()
                        updateManageUsersSummary()
                    }
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun showRemoveUserDialog(username: String) {
        val context = requireContext()

        AlertDialog.Builder(context)
            .setTitle("Remove User")
            .setMessage("Remove user '$username'?")
            .setPositiveButton("Remove") { _, _ ->
                CredentialManager.removeCredential(context, username)
                Toast.makeText(context, "User '$username' removed", Toast.LENGTH_SHORT).show()
                updateManageUsersSummary()
            }
            .setNegativeButton("Cancel", null)
            .show()
    }
}
