using System;
using PrimeTween;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace AlicizaX.UI.RecyclerView
{
    public class ScrollbarEx : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IPointerEnterHandler, IPointerExitHandler
    {
        private RectTransform handle;
        private Scrollbar scrollbar;

        public Action OnDragEnd;

        private bool dragging;
        private bool hovering;

        private void Awake()
        {
            scrollbar = GetComponent<Scrollbar>();
            handle = scrollbar.handleRect;
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            dragging = true;
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            dragging = false;
            if (!hovering)
            {
                if (scrollbar.direction == Scrollbar.Direction.TopToBottom ||
                    scrollbar.direction == Scrollbar.Direction.BottomToTop)
                {
                    Tween.ScaleX(handle, 1f, 0.2f);
                }
                else
                {
                    Tween.ScaleY(handle, 1f, 0.2f);
                }
            }

            OnDragEnd?.Invoke();
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            hovering = true;
            if (scrollbar.direction == Scrollbar.Direction.TopToBottom ||
                scrollbar.direction == Scrollbar.Direction.BottomToTop)
            {
                Tween.ScaleX(handle, 2f, 0.2f);
            }
            else
            {
                Tween.ScaleY(handle, 2f, 0.2f);
            }
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            hovering = false;
            if (!dragging)
            {
                if (scrollbar.direction == Scrollbar.Direction.TopToBottom ||
                    scrollbar.direction == Scrollbar.Direction.BottomToTop)
                {
                    Tween.ScaleX(handle, 1f, 0.2f);
                }
                else
                {
                    Tween.ScaleY(handle, 1f, 0.2f);
                }
            }
        }
    }
}
