using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class ToastsPanel : MonoBehaviour
  {
    private const float ToastLifetimeSeconds = 4.2f;

    [SerializeField] private PanelRenderer panelRenderer;
    [SerializeField] private CozyCollectorController controller;
    [SerializeField] private VisualTreeAsset toastTemplate;

    private readonly List<ToastView> _toasts = new List<ToastView>();
    private readonly List<float> _dismissAt = new List<float>();

    private VisualElement _container;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.ToastRequested += HandleToastRequested;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.ToastRequested -= HandleToastRequested;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _container = root.Q("toasts");
    }

    private void Update()
    {
      for (int i = _toasts.Count - 1; i >= 0; i--)
      {
        if (Time.unscaledTime >= _dismissAt[i])
        {
          Dismiss(i);
        }
      }
    }

    private void HandleToastRequested(string title, string message, CozyToastTone tone)
    {
      var root = toastTemplate.CloneTree();
      _container.Add(root);

      var toast = new ToastView(root);
      toast.Set(title, message, tone);
      toast.Root.RegisterCallback<ClickEvent>(_ => Dismiss(toast));

      _toasts.Add(toast);
      _dismissAt.Add(Time.unscaledTime + ToastLifetimeSeconds);
    }

    private void Dismiss(ToastView toast)
    {
      int index = _toasts.IndexOf(toast);
      if (index >= 0)
      {
        Dismiss(index);
      }
    }

    private void Dismiss(int index)
    {
      var toast = _toasts[index];
      _toasts.RemoveAt(index);
      _dismissAt.RemoveAt(index);
      toast.Root.RemoveFromHierarchy();
    }
  }
}
