using System;
using KitsuneCafe.ItemSystem;
using KitsuneCafe.SOAP;
using KitsuneCafe.UI.MVVM;
using R3;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace KitsuneCafe.UI
{
  public class InventoryScreen : MonoBehaviour
  {
    public const string ItemListIndicatorsName = "item-list-indicator";
    public const string ItemListName = "item-list";

    public const string ItemPreviewName = "item-preview";


    public const string ItemDetailsTitleName = "item-details-title-label";
    public const string ItemDetailsContentName = "item-details-content-label";

    [SerializeField]
    private UIDocument doc;

    [SerializeField]
    private Inventory inventory;

    [SerializeField]
    private VisualTreeAsset template;

    [SerializeField]
    private int displayCount = 5;

    [SerializeField]
    private ItemValue selectedItem;

    [SerializeField]
    private FloatEvent inventoryInput;

    [SerializeField]
    private Vector2Value itemPreviewDelta;

    [SerializeField]
    private FloatValue itemZoom;

    [SerializeField]
    private ActionMapValue actionMap;

    private VisualElement root => doc.rootVisualElement;

    private VisualElement indicators;
    private VisualElement itemPreview;

    private void OnValidate()
    {
      if (doc == null)
      {
        doc = GetComponent<UIDocument>();
      }
    }

    private void Reset()
    {
      OnValidate();
    }

    private void Start()
    {
      root.visible = false;

      inventoryInput.AsObservable()
        .Subscribe(_ =>
        {
          root.visible = !root.visible;
          actionMap.Value = root.visible ? Input.ActionMap.UI : Input.ActionMap.Player;
        });

      CreateItemList();
      var preview = root.Q<PreviewView>();

      preview.RegisterCallback<RotateEvent>(evt =>
      {
        itemPreviewDelta.Value = evt.Delta;
      });

      preview.RegisterCallback<ZoomEvent>(evt =>
      {
        itemZoom.Value += evt.Amount;
      });
    }

    private void CreateItemList()
    {
      var itemList = root.Q<RecyclerView>();
      itemList.ItemSource = inventory;
      itemList.Binder = new AdHocBinder(
        () =>
        {
          var instance = template.CloneTree();
          instance.focusable = true;
          return instance;
        },
        (el, i) =>
        {
          el.dataSource = inventory[i];
        },
        el =>
        {
          el.dataSource = null;
        }
      );

      itemList.RegisterCallback<SelectEvent>(evt =>
      {
        Debug.Log($"Selected {evt.DataIndex}");
      });
    }
  }
}
