using System;
using JetBrains.Annotations;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.UI;
#if ODIN_INSPECTOR
#endif

namespace JohnsonUtils.Canvases
{
    public class ButtonUIComponent : UISelectableComponentBase
    {
        public event Action OnClick;

#if ODIN_INSPECTOR
        [Required]
#endif
        [Header("Association"), SerializeField]
        private Button button;

        [Header("Configuration"), SerializeField, UsedImplicitly]
        private ButtonNavigationType buttonNavigationType;
        
        private enum ButtonNavigationType
        {
            [UsedImplicitly] Forward,
            [UsedImplicitly] Backward
        }

        public Color Color
        {
            set => button.image.color = value;
        }

        [PublicAPI]
        public bool Enabled
        {
            set => button.interactable = value;
        }

        [PublicAPI]
        public void Select() => button.Select();

        protected override void SetSelectableGameObject() => Selectable = button;

        private void Start()
        {
            Debug.Assert(button, $"A {nameof(button)} must be assigned to a {nameof(ButtonUIComponent)}");
            button.onClick.AddListener(OnButtonClicked);
        }

        protected override void OnDestroy()
        {
            button.onClick.RemoveListener(OnButtonClicked);
            base.OnDestroy();
        }

        private void OnButtonClicked()
        {
            OnClick?.Invoke();
        }

        private void OnValidate()
        {
            if (!button)
                button = GetComponent<Button>();
        }
    }
}