using System.Text;
using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class HudPanel : MonoBehaviour
  {
    private const string TimerLowClass = "timer-low";

    [SerializeField] private PanelRenderer panelRenderer;
    [SerializeField] private CozyCollectorController controller;
    [SerializeField] private GameWorld world;

    private Label _scoreLabel;
    private Label _bestLabel;
    private Label _timeLeftLabel;
    private VisualElement _timerFill;
    private Label _walletLabel;
    private Button _shopButton;
    private Button _backpackButton;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      world.StateChanged += Refresh;
      world.RoundFinished += HandleRoundFinished;
      controller.WalletsChanged += RefreshWallet;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      world.StateChanged -= Refresh;
      world.RoundFinished -= HandleRoundFinished;
      controller.WalletsChanged -= RefreshWallet;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _scoreLabel = root.Q<Label>("hud-score");
      _bestLabel = root.Q<Label>("hud-best");
      _timeLeftLabel = root.Q<Label>("hud-time-left");
      _timerFill = root.Q("hud-timer-fill");
      _walletLabel = root.Q<Label>("hud-wallet");
      _shopButton = root.Q<Button>("hud-shop-button");
      _backpackButton = root.Q<Button>("hud-backpack-button");

      _shopButton.clicked -= HandleShopClicked;
      _shopButton.clicked += HandleShopClicked;
      _backpackButton.clicked -= HandleBackpackClicked;
      _backpackButton.clicked += HandleBackpackClicked;

      Refresh();
      RefreshWallet();
    }

    private void Update()
    {
      RefreshTimer();
    }

    private void Refresh()
    {
      _scoreLabel.text = world.Score.ToString();
      _bestLabel.text = controller.Save != null ? controller.Save.BestScore.ToString() : "0";
      RefreshTimer();
    }

    private void RefreshTimer()
    {
      float roundSeconds = controller.Tuning != null ? Mathf.Max(1f, controller.Tuning.RoundSeconds) : 1f;
      float fraction = Mathf.Clamp01(world.TimeLeftSeconds / roundSeconds);
      _timeLeftLabel.text = $"{Mathf.CeilToInt(Mathf.Max(0f, world.TimeLeftSeconds))}s";
      _timerFill.style.width = Length.Percent(fraction * 100f);
      _timerFill.EnableInClassList(TimerLowClass, fraction <= 0.2f);
    }

    private void RefreshWallet()
    {
      _walletLabel.text = WalletLabel();
    }

    private string WalletLabel()
    {
      var wallets = controller.Wallets;
      if (wallets == null || wallets.Count == 0)
      {
        return "—";
      }

      var builder = new StringBuilder();
      foreach (var wallet in wallets)
      {
        if (builder.Length > 0)
        {
          builder.Append(" · ");
        }
        builder.Append($"{wallet.Balance:0.##} {wallet.Currency}".TrimEnd());
      }
      return builder.ToString();
    }

    private void HandleRoundFinished(int score, int collected)
    {
      Refresh();
    }

    private void HandleShopClicked()
    {
      controller.OpenModal(CozyModal.Shop);
    }

    private void HandleBackpackClicked()
    {
      controller.OpenModal(CozyModal.Backpack);
    }
  }
}
