using Player;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;
using TMPro;

public class SettingsManager : MonoBehaviour
{
    [Header("Audio")]
    [SerializeField] private AudioMixer mainMixer;
    [SerializeField] private Slider masterVolumeSlider;

    [Header("Sensitivity")]
    [SerializeField] private Slider sensitivitySlider;
    [SerializeField] private TMP_InputField sensitivityInputField;
    [SerializeField] private PlayerController playerController;

    [Header("Brightness")]
    [SerializeField] private Slider brightnessSlider;
    [SerializeField] private BrightnessController brightnessController;

    // PlayerPrefs Keys
    private const string MASTER_VOLUME_KEY = "MasterVolume";
    private const string SENSITIVITY_KEY = "MouseSensitivity";
    private const string BRIGHTNESS_KEY = "ScreenBrightness";

    private void Start()
    {
        // First, load all saved values and apply them WITHOUT triggering events.
        LoadInitialValues();

        // NOW, after everything is set up, subscribe to user-driven changes.
        SubscribeToEvents();
    }

    private void LoadInitialValues()
    {
        // --- Volume ---
        float masterVolume = PlayerPrefs.GetFloat(MASTER_VOLUME_KEY, 0.75f);
        masterVolumeSlider.SetValueWithoutNotify(masterVolume); // Use WithoutNotify to prevent event firing
        ApplyMasterVolume(masterVolume);

        // --- Sensitivity ---
        float maxSensitivity = sensitivitySlider.maxValue;
        float sensitivity = PlayerPrefs.GetFloat(SENSITIVITY_KEY, maxSensitivity / 2);
        sensitivitySlider.SetValueWithoutNotify(sensitivity);
        sensitivityInputField.SetTextWithoutNotify(sensitivity.ToString("F1")); // Use WithoutNotify
        ApplySensitivity(sensitivity);

        // --- Brightness ---
        float brightness = PlayerPrefs.GetFloat(BRIGHTNESS_KEY, 0.5f);
        brightnessSlider.SetValueWithoutNotify(brightness);
        ApplyBrightness(brightness);
    }

    private void SubscribeToEvents()
    {
        masterVolumeSlider.onValueChanged.AddListener(OnMasterVolumeChanged);
        sensitivitySlider.onValueChanged.AddListener(OnSensitivitySliderChanged);
        sensitivityInputField.onEndEdit.AddListener(OnSensitivityInputChanged);
        brightnessSlider.onValueChanged.AddListener(OnBrightnessChanged);
    }

    // --- Event Handlers ---

    private void OnMasterVolumeChanged(float value)
    {
        ApplyMasterVolume(value);
        PlayerPrefs.SetFloat(MASTER_VOLUME_KEY, value);
    }

    private void OnSensitivitySliderChanged(float value)
    {
        sensitivityInputField.SetTextWithoutNotify(value.ToString("F1"));
        ApplySensitivity(value);
        PlayerPrefs.SetFloat(SENSITIVITY_KEY, value);
    }

    private void OnSensitivityInputChanged(string textValue)
    {
        if (float.TryParse(textValue, out float value))
        {
            value = Mathf.Clamp(value, sensitivitySlider.minValue, sensitivitySlider.maxValue);
            sensitivitySlider.SetValueWithoutNotify(value); // This will NOT trigger the slider's event
            ApplySensitivity(value); // So we must apply the change manually
            PlayerPrefs.SetFloat(SENSITIVITY_KEY, value);
        }
        else
        {
            sensitivityInputField.SetTextWithoutNotify(sensitivitySlider.value.ToString("F1"));
        }
    }

    private void OnBrightnessChanged(float value)
    {
        ApplyBrightness(value);
        PlayerPrefs.SetFloat(BRIGHTNESS_KEY, value);
    }

    // --- Apply Logic ---

    private void ApplyMasterVolume(float value)
    {
        if (mainMixer == null) return;
        // Use a small epsilon to prevent Log10(0) = -Infinity
        float dbValue = Mathf.Log10(Mathf.Max(value, 0.0001f)) * 20;
        mainMixer.SetFloat("MasterVolume", dbValue);
    }

    private void ApplySensitivity(float value)
    {
        if (playerController != null)
        {
            playerController.mouseSensitivity = value;
        }
    }

    private void ApplyBrightness(float value)
    {
        if (brightnessController != null)
        {
            brightnessController.SetBrightness(value);
        }
    }

    // Unsubscribe on destroy to prevent memory leaks
    private void OnDestroy()
    {
        masterVolumeSlider?.onValueChanged.RemoveListener(OnMasterVolumeChanged);
        sensitivitySlider?.onValueChanged.RemoveListener(OnSensitivitySliderChanged);
        sensitivityInputField?.onEndEdit.RemoveListener(OnSensitivityInputChanged);
        brightnessSlider?.onValueChanged.RemoveListener(OnBrightnessChanged);
    }
}