package com.rugvedsarika.toolbox

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.appcompat.app.AppCompatDelegate
import com.rugvedsarika.toolbox.databinding.FragmentSettingsBinding

class SettingsFragment : Fragment() {

    private var _binding: FragmentSettingsBinding? = null
    private val binding get() = _binding!!
    private lateinit var preferenceManager: PreferenceManager

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        preferenceManager = PreferenceManager(requireContext())

        setupToolbar()
        setupThemeSelection()
        
        binding.cardFavoriteTools.setOnClickListener {
            findNavController().navigate(R.id.action_settingsFragment_to_favoriteToolsFragment)
        }
    }

    private fun setupToolbar() {
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun setupThemeSelection() {
        val currentMode = preferenceManager.getThemeMode()
        when (currentMode) {
            PreferenceManager.MODE_LIGHT -> binding.radioLight.isChecked = true
            PreferenceManager.MODE_DARK -> binding.radioDark.isChecked = true
            else -> binding.radioSystem.isChecked = true
        }

        binding.radioGroupTheme.setOnCheckedChangeListener { _, checkedId ->
            val mode = when (checkedId) {
                R.id.radio_light -> PreferenceManager.MODE_LIGHT
                R.id.radio_dark -> PreferenceManager.MODE_DARK
                else -> PreferenceManager.MODE_SYSTEM
            }
            preferenceManager.setThemeMode(mode)
            applyTheme(mode)
        }
    }

    private fun applyTheme(mode: Int) {
        when (mode) {
            PreferenceManager.MODE_LIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            PreferenceManager.MODE_DARK -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
