using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class RoundResultModalPanel : MonoBehaviour
  {
    private const int MaxLeaderboardRows = 10;

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

    private VisualElement root;
    private Label scoreLabel;
    private Label bestLabel;
    private Label collectedLabel;
    private ScrollView leaderboardScroll;
    private VisualElement emptyNote;
    private Button playAgainButton;
    private Button claimButton;
    private Button endButton;
    private Button closeButton;

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

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

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      this.root = root.Q<VisualElement>("round-result-modal");
      scoreLabel = this.root.Q<Label>("rr-score");
      bestLabel = this.root.Q<Label>("rr-best");
      collectedLabel = this.root.Q<Label>("rr-collected");
      leaderboardScroll = this.root.Q<ScrollView>("rr-leaderboard-scroll");
      emptyNote = this.root.Q<VisualElement>("rr-empty");
      playAgainButton = this.root.Q<Button>("rr-play-again-button");
      claimButton = this.root.Q<Button>("rr-claim-button");
      endButton = this.root.Q<Button>("rr-end-button");
      closeButton = this.root.Q<Button>("rr-close-button");

      playAgainButton.clicked -= HandlePlayAgainClicked;
      playAgainButton.clicked += HandlePlayAgainClicked;
      claimButton.clicked -= HandleClaimClicked;
      claimButton.clicked += HandleClaimClicked;
      endButton.clicked -= HandleEndClicked;
      endButton.clicked += HandleEndClicked;
      closeButton.clicked -= HandleCloseClicked;
      closeButton.clicked += HandleCloseClicked;

      ApplyVisibility();
      Refresh();
    }

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

    private void Refresh()
    {
      var result = controller.RoundResult;
      scoreLabel.text = result != null ? result.Score.ToString() : "0";
      bestLabel.text = result != null ? result.Best.ToString() : "0";
      collectedLabel.text = result != null ? result.Collected.ToString() : "0";

      leaderboardScroll.Clear();

      var entries = result != null ? result.TopEntries : null;
      emptyNote.style.display = entries == null || entries.Count == 0 ? DisplayStyle.Flex : DisplayStyle.None;
      if (entries == null)
      {
        return;
      }

      int count = Mathf.Min(entries.Count, MaxLeaderboardRows);
      for (int i = 0; i < count; i++)
      {
        var entry = entries[i];
        var rowRoot = leaderboardRowTemplate.CloneTree();
        var row = new LeaderboardRowView(rowRoot);
        row.Set(entry.Rank, string.IsNullOrEmpty(entry.PlayerName) ? "player" : entry.PlayerName, entry.Score);
        leaderboardScroll.Add(rowRoot);
      }
    }

    private void HandlePlayAgainClicked()
    {
      controller.PlayAgain();
    }

    private void HandleClaimClicked()
    {
      controller.ClaimScenarioLeaderboardReward();
    }

    private void HandleEndClicked()
    {
      controller.EndScenarioLeaderboard();
    }

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