package com.crm.chat.ui.settings

import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import com.crm.chat.databinding.ActivitySettingsBinding

class SettingsActivity : AppCompatActivity() {

    private lateinit var binding: ActivitySettingsBinding
    private lateinit var prefs: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySettingsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        prefs = getSharedPreferences("crm_chat_prefs", MODE_PRIVATE)

        setupToolbar()
        loadCurrentSettings()
        setupListeners()
    }

    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "Настройки"
    }

    private fun loadCurrentSettings() {
        val serverUrl = prefs.getString("server_url", "")
        val apiKey = prefs.getString("api_key", "")
        val currentThemeMode = prefs.getInt("theme_mode", AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)

        binding.serverUrlEditText.setText(serverUrl)
        binding.apiKeyEditText.setText(apiKey)

        // Set theme switch based on current mode
        binding.themeSwitch.isChecked = when (currentThemeMode) {
            AppCompatDelegate.MODE_NIGHT_YES -> true
            else -> false
        }
    }

    private fun setupListeners() {
        binding.saveButton.setOnClickListener {
            saveSettings()
        }

        binding.themeSwitch.setOnCheckedChangeListener { _, isChecked ->
            // Immediately apply theme change
            val newMode = if (isChecked) {
                AppCompatDelegate.MODE_NIGHT_YES
            } else {
                AppCompatDelegate.MODE_NIGHT_NO
            }
            AppCompatDelegate.setDefaultNightMode(newMode)

            // Save preference
            prefs.edit().putInt("theme_mode", newMode).apply()
        }
    }

    private fun saveSettings() {
        val serverUrl = binding.serverUrlEditText.text.toString().trim()
        val apiKey = binding.apiKeyEditText.text.toString().trim()

        if (serverUrl.isEmpty()) {
            binding.errorTextView.text = "Введите адрес сервера"
            binding.errorTextView.visibility = android.view.View.VISIBLE
            return
        }

        if (apiKey.isEmpty()) {
            binding.errorTextView.text = "Введите API-ключ"
            binding.errorTextView.visibility = android.view.View.VISIBLE
            return
        }

        // Save to preferences
        prefs.edit()
            .putString("server_url", serverUrl)
            .putString("api_key", apiKey)
            .apply()

        binding.errorTextView.visibility = android.view.View.GONE
        Toast.makeText(this, "Настройки сохранены", Toast.LENGTH_SHORT).show()
        finish()
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressedDispatcher.onBackPressed()
        return true
    }
}
