using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class InventorySlot : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler, IPointerMoveHandler, IPointerClickHandler
{
    public int SlotIndex; // 슬롯의 고유 번호
    private RectTransform _rectTransform; //슬롯박스 사각형

    [Header("Slot References")]
    [SerializeField] private Image _iconImage;
    [SerializeField] private TextMeshProUGUI _stackText;
    [SerializeField] private Image _rarityImage; // 등급 배경 등
    [SerializeField] private GameObject _highlightBox;

    [Header("Slot Settings")]
    [SerializeField] private Sprite _rarity_None_Sprite;
    [SerializeField] private Sprite _rarity_1_Sprite;
    [SerializeField] private Sprite _rarity_2_Sprite;
    [SerializeField] private Sprite _rarity_3_Sprite;
    [SerializeField] private Sprite _rarity_4_Sprite;

    [Header("Current ItemInstance")]
    public ItemInstance currentItem; // 이 슬롯에 담긴 아이템 정보

    //private Image SlotBg; //기본 슬롯 배경

    private void Awake()
    {
        //SlotBg = GetComponent<Image>();
        _rectTransform = GetComponent<RectTransform>();
        ClearSlot();
    }

    private void Start()
    {
        if (currentItem != null)
            SetItem(currentItem);
    }

    public void ClearSlot()
    {
        _iconImage.sprite = null;
        _iconImage.enabled = false;

        _stackText.text = "";
        _stackText.enabled = false;

        _rarityImage.sprite = _rarity_None_Sprite;
        //SlotBg.sprite = RarityImage.sprite;
    }

    public void UpdateSlotUI()
    {
        if (currentItem == null)
        {
            ClearSlot();
            return;
        }

        if (currentItem.Data.Icon != null)
        {
            _iconImage.sprite = currentItem.Data.Icon;
            _iconImage.enabled = true;
        }

        if (currentItem.Data.IsStackable)
            _stackText.text = currentItem.CurrentStack.ToString();
        else
            _stackText.text = "";

        _stackText.enabled = true;

        switch (currentItem.Data.Rarity)
        {
            case 1:
                {
                    _rarityImage.sprite = _rarity_1_Sprite;
                }
                break;
            case 2:
                {
                    _rarityImage.sprite = _rarity_2_Sprite;
                }
                break;
            case 3:
                {
                    _rarityImage.sprite = _rarity_3_Sprite;
                }
                break;
            case 4:
                {
                    _rarityImage.sprite = _rarity_4_Sprite;
                }
                break;
            default:
                {
                    _rarityImage.sprite = _rarity_None_Sprite;
                }
                break;

        }
        //SlotBg.sprite = _rarityImage.sprite;
    }

    // 아이템 데이터 설정 및 UI 갱신
    public void SetItem(ItemInstance newItem)
    {
        currentItem = newItem;

        UpdateSlotUI();
    }

    public void OnDrop(PointerEventData eventData)
    {
        GameObject dropped = eventData.pointerDrag;
        if (dropped != null)
        {
            InventoryItemControl dragItem = dropped.GetComponent<InventoryItemControl>();
            if (dragItem != null)
            {
                InventorySlot originalSlot = dragItem.ParentSlot;

                if (originalSlot != null && originalSlot != this)
                {
                    // 스택 가능한 아이템이고 개수가 1개보다 많을 때만 분할 창 띄우기
                    if (originalSlot.currentItem.Data.IsStackable && originalSlot.currentItem.CurrentStack > 1)
                    {
                        // 팝업 오픈 (Action으로 분할 로직 전달)
                        GameManager.Instance.InGameUI.GetSplitWindowUI().Open(originalSlot.currentItem.CurrentStack, (splitCount) =>
                        {
                            GameManager.Instance.Inventory.ExecuteSplit(originalSlot.SlotIndex, this.SlotIndex, splitCount);
                        });
                    }
                    else
                    {
                        Debug.Log($"{originalSlot.SlotIndex}번 슬롯에서 {this.SlotIndex}번 슬롯으로 이동 시도");
                        GameManager.Instance.Inventory.MoveItem(originalSlot.SlotIndex, this.SlotIndex);
                    }
                }
            }
        }
    }
    public void OnPointerEnter(PointerEventData eventData)
    {
        if (currentItem != null && currentItem.Data != null)
        {
            // 드래그 중에는 툴팁 안띄움
            if (eventData.dragging)
            {
                _highlightBox.gameObject.SetActive(false);
                GameManager.Instance.InGameUI.Tooltip.HideTooltip();
                return;
            }

            _highlightBox.gameObject.SetActive(true);
            GameManager.Instance.InGameUI.Tooltip.ShowTooltip(currentItem, GetComponent<RectTransform>());
        }
    }


    public void OnPointerMove(PointerEventData eventData)
    {
        if (currentItem != null && currentItem.Data != null)
        {
            // 드래그 중이거나, 현재 마우스 위치를 로컬 좌표로 변환해서 사각형 안에 있지 않으면
            if (eventData.dragging || !RectTransformUtility.RectangleContainsScreenPoint(_rectTransform, eventData.position, eventData.pressEventCamera))
            {
                _highlightBox.gameObject.SetActive(false);
                GameManager.Instance.InGameUI.Tooltip.HideTooltip();
                return;
            }

            _highlightBox.gameObject.SetActive(true);
            GameManager.Instance.InGameUI.Tooltip.ShowTooltip(currentItem, GetComponent<RectTransform>());
        }
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        _highlightBox.gameObject.SetActive(false);
        GameManager.Instance.InGameUI.Tooltip.HideTooltip();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        // 우클릭
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            if(currentItem != null) //아이템이 존재할시에만 사용
            {
                GameManager.Instance.Inventory.ItemUse(SlotIndex);
            }
        }
    }
}