package com.jordanbot.autoride

import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.Switch
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jordanbot.autoride.filter.FilterEngine

class SettingsActivity : AppCompatActivity() {

    private lateinit var etMinPrice: EditText
    private lateinit var etMaxMinutes: EditText
    private lateinit var switchAutoAccept: Switch
    private lateinit var cbUber: CheckBox
    private lateinit var cbCareem: CheckBox
    private lateinit var cbJeeny: CheckBox
    private lateinit var switchDarkMode: Switch
    private lateinit var btnSave: Button

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

        etMinPrice = findViewById(R.id.et_min_price)
        etMaxMinutes = findViewById(R.id.et_max_minutes)
        switchAutoAccept = findViewById(R.id.switch_auto_accept)
        cbUber = findViewById(R.id.cb_uber)
        cbCareem = findViewById(R.id.cb_careem)
        cbJeeny = findViewById(R.id.cb_jeeny)
        switchDarkMode = findViewById(R.id.switch_dark_mode)
        btnSave = findViewById(R.id.btn_save_settings)

        loadCurrentSettings()

        btnSave.setOnClickListener {
            saveSettings()
        }
    }

    private fun loadCurrentSettings() {
        FilterEngine.init(this)
        etMinPrice.setText(FilterEngine.minPriceJod.toString())
        etMaxMinutes.setText(FilterEngine.maxMinutesAway.toString())
        switchAutoAccept.isChecked = FilterEngine.isEnabled
        cbUber.isChecked = FilterEngine.enableUber
        cbCareem.isChecked = FilterEngine.enableCareem
        cbJeeny.isChecked = FilterEngine.enableJeeny
        
        val prefs = getSharedPreferences("ThemePrefs", MODE_PRIVATE)
        switchDarkMode.isChecked = prefs.getBoolean("dark_mode", true)
    }

    private fun saveSettings() {
        val price = etMinPrice.text.toString().toDoubleOrNull() ?: 1.0
        val minutes = etMaxMinutes.text.toString().toIntOrNull() ?: 10
        val autoAccept = switchAutoAccept.isChecked
        val uber = cbUber.isChecked
        val careem = cbCareem.isChecked
        val jeeny = cbJeeny.isChecked

        FilterEngine.save(price, minutes, autoAccept, uber, careem, jeeny)

        val prefs = getSharedPreferences("ThemePrefs", MODE_PRIVATE)
        val currentDark = prefs.getBoolean("dark_mode", true)
        val newDark = switchDarkMode.isChecked
        
        prefs.edit().putBoolean("dark_mode", newDark).apply()

        Toast.makeText(this, "تم حفظ الإعدادات بنجاح", Toast.LENGTH_SHORT).show()
        
        if (currentDark != newDark) {
            // Theme changed, restart app or recreate
            Toast.makeText(this, "يرجى إعادة تشغيل التطبيق لتطبيق المظهر الجديد", Toast.LENGTH_LONG).show()
        }
        
        finish()
    }
}
