package com.example.time_tracking

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class SettingsActivity : AppCompatActivity() {

    private lateinit var etMinGoal: EditText
    private lateinit var etMaxGoal: EditText
    private lateinit var btnSaveSettings: Button

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

        // Initialize views
        etMinGoal = findViewById(R.id.etMinGoal)
        etMaxGoal = findViewById(R.id.etMaxGoal)
        btnSaveSettings = findViewById(R.id.btnSaveSettings)

        // Load settings
        val sharedPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE)
        val minGoal = sharedPreferences.getInt("minGoal", 0)
        val maxGoal = sharedPreferences.getInt("maxGoal", 0)
        etMinGoal.setText(minGoal.toString())
        etMaxGoal.setText(maxGoal.toString())

        // Save settings button click listener
        btnSaveSettings.setOnClickListener {
            val minGoal = etMinGoal.text.toString().toIntOrNull()
            val maxGoal = etMaxGoal.text.toString().toIntOrNull()

            if (minGoal != null && maxGoal != null) {
                // Both minGoal and maxGoal have valid values
                saveSettings()
                // Show success message
                Toast.makeText(this, "Settings saved successfully", Toast.LENGTH_SHORT).show()
            } else {
                // One or both of the values are invalid or empty
                // Show error message
                Toast.makeText(this, "Invalid goal values", Toast.LENGTH_SHORT).show()
            }
        }


        // Back to menu button click listener
        val btnBackToMenu: Button = findViewById(R.id.btnBackToMenu)
        btnBackToMenu.setOnClickListener {
            // Navigate back to the menu activity
            val intent = Intent(this, MenuActivity::class.java)
            startActivity(intent)
            finish() // Optional: Close the current activity
        }
    }

    private fun saveSettings() {
        // Get values from EditTexts
        val minGoal = etMinGoal.text.toString().toIntOrNull() ?: 0
        val maxGoal = etMaxGoal.text.toString().toIntOrNull() ?: 0

        // Save settings to SharedPreferences
        val sharedPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putInt("minGoal", minGoal)
        editor.putInt("maxGoal", maxGoal)
        editor.apply()

        // Optionally, you can provide feedback to the user that settings are saved
        // For example:
        // Toast.makeText(this, "Settings saved successfully", Toast.LENGTH_SHORT).show()
    }
}

