using System;
using UnityEngine;
using UnityEngine.UI;

namespace Darkmatter.Libs.UI
{
    /// <summary>
    /// A single reusable toggle button component.
    /// Handles its own state and visual updates while exposing an event for Presenters.
    /// </summary>
    [RequireComponent(typeof(Button))]
    public class ToggleButton : MonoBehaviour
    {
        [Header("States")] [SerializeField] private GameObject onObject;
        [SerializeField] private GameObject offObject;

        private Button _button;

        [Header("Initial State")] [SerializeField]
        private bool isOn;

        public event Action<bool> OnValueChanged;

        public bool IsOn
        {
            get => isOn;
            set
            {
                if (isOn == value) return;
                isOn = value;
                UpdateVisuals();
                OnValueChanged?.Invoke(isOn);
            }
        }

        private void Awake()
        {
            _button = GetComponent<Button>();
            if (_button != null)
            {
                _button.onClick.AddListener(Toggle);
            }

            UpdateVisuals();
        }

        private void Toggle()
        {
            IsOn = !IsOn;
        }

        public void SetStateSilently(bool newState)
        {
            isOn = newState;
            UpdateVisuals();
        }

        private void UpdateVisuals()
        {
            if (onObject != null) onObject.SetActive(isOn);
            if (offObject != null) offObject.SetActive(!isOn);
        }

        public void SetInteractable(bool interactable)
        {
            if (_button != null) _button.interactable = interactable;
        }
    }
}