package com.rugvedsarika.cashcounter

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.rugvedsarika.cashcounter.data.AppDatabase
import com.rugvedsarika.cashcounter.databinding.ActivitySettingsBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SettingsActivity : AppCompatActivity() {

    private lateinit var binding: ActivitySettingsBinding

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

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        binding.toolbar.setNavigationOnClickListener { finish() }

        // Setup Haptics Toggle (Simple logic, just simple persistence in SharedPreferences if needed, 
        // but for now relying on user expectation. The actual haptics in MainActivity are hardcoded to ON 
        // as per previous code. To implement toggle properly, I'd need to use SharedPrefs.)
        
        val prefs = getSharedPreferences("app_prefs", MODE_PRIVATE)
        binding.switchHaptics.isChecked = prefs.getBoolean("haptics_enabled", true)
        
        binding.switchHaptics.setOnCheckedChangeListener { _, isChecked ->
            prefs.edit().putBoolean("haptics_enabled", isChecked).apply()
        }

        // Language Selection
        val currentLang = prefs.getString("language_code", "en")
        when (currentLang) {
            "en" -> binding.rbEnglish.isChecked = true
            "hi" -> binding.rbHindi.isChecked = true
            "mr" -> binding.rbMarathi.isChecked = true
        }

        binding.radioGroupLanguage.setOnCheckedChangeListener { _, checkedId ->
            val langCode = when (checkedId) {
                R.id.rbHindi -> "hi"
                R.id.rbMarathi -> "mr"
                else -> "en"
            }
            prefs.edit().putString("language_code", langCode).apply()
        }

        binding.btnClearHistory.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle("Clear History")
                .setMessage("Are you sure you want to delete all saved records? This cannot be undone.")
                .setPositiveButton("Delete") { _, _ ->
                    lifecycleScope.launch(Dispatchers.IO) {
                        AppDatabase.getDatabase(this@SettingsActivity).historyDao().deleteAll()
                        withContext(Dispatchers.Main) {
                            Toast.makeText(this@SettingsActivity, "History Cleared", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                .setNegativeButton("Cancel", null)
                .show()
        }
    }
}
