using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class BackpackModalPanel : MonoBehaviour
  {
    [SerializeField] private PanelRenderer panelRenderer;
    [SerializeField] private CozyCollectorController controller;
    [SerializeField] private VisualTreeAsset backpackItemRowTemplate;
    [SerializeField] private CozyCollectorSpriteLibrary spriteLibrary;

    private VisualElement _root;
    private ScrollView _itemsScroll;
    private VisualElement _emptyNote;
    private Button _closeButton;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.ModalChanged += ApplyVisibility;
      controller.BackpackChanged += Rebuild;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.ModalChanged -= ApplyVisibility;
      controller.BackpackChanged -= Rebuild;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _root = root.Q<VisualElement>("backpack-modal");
      _itemsScroll = _root.Q<ScrollView>("backpack-items-scroll");
      _emptyNote = _root.Q<VisualElement>("backpack-empty");
      _closeButton = _root.Q<Button>("backpack-close-button");

      _closeButton.clicked -= HandleCloseClicked;
      _closeButton.clicked += HandleCloseClicked;

      ApplyVisibility();
      Rebuild();
    }

    private void ApplyVisibility()
    {
      _root.style.display = controller.ActiveModal == CozyModal.Backpack ? DisplayStyle.Flex : DisplayStyle.None;
    }

    private void Rebuild()
    {
      _itemsScroll.contentContainer.Clear();

      var items = controller.BackpackItems;
      _emptyNote.style.display = items == null || items.Count == 0 ? DisplayStyle.Flex : DisplayStyle.None;
      if (items == null)
      {
        return;
      }

      foreach (var item in items)
      {
        var rowRoot = backpackItemRowTemplate.CloneTree();
        _itemsScroll.contentContainer.Add(rowRoot);

        var row = new BackpackItemRowView(rowRoot);
        row.Set(
          spriteLibrary.ForSlug(item.Slug),
          string.IsNullOrEmpty(item.Name) ? item.Slug : item.Name,
          item.Slug,
          item.Amount);
      }
    }

    private void HandleCloseClicked()
    {
      controller.CloseModal();
    }
  }
}
