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

namespace LiveOpsExamples
{
  public class SessionCardPanel : MonoBehaviour
  {
    [SerializeField] private PanelRenderer panelRenderer;
    [SerializeField] private CozyCollectorController controller;

    private Label _nicknameLabel;
    private Label _playerIdLabel;
    private Label _deviceIdLabel;
    private Label _regionLabel;
    private Label _projectKeyLabel;
    private Label _walletsLabel;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.PhaseChanged += Refresh;
      controller.WalletsChanged += RefreshWallets;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.PhaseChanged -= Refresh;
      controller.WalletsChanged -= RefreshWallets;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _nicknameLabel = root.Q<Label>("session-nickname");
      _playerIdLabel = root.Q<Label>("session-player-id");
      _deviceIdLabel = root.Q<Label>("session-device-id");
      _regionLabel = root.Q<Label>("session-region");
      _projectKeyLabel = root.Q<Label>("session-project-key");
      _walletsLabel = root.Q<Label>("session-wallets");

      Refresh();
    }

    private void Refresh()
    {
      var identity = controller.Identity;
      if (identity == null)
      {
        _nicknameLabel.text = "—";
        _playerIdLabel.text = "—";
        _deviceIdLabel.text = "—";
        _regionLabel.text = "—";
        _projectKeyLabel.text = "—";
      }
      else
      {
        _nicknameLabel.text = string.IsNullOrEmpty(identity.Nickname)
          ? $"Player {identity.PlayerId.Substring(0, Mathf.Min(6, identity.PlayerId.Length))}"
          : identity.Nickname;
        _playerIdLabel.text = identity.PlayerId;
        _deviceIdLabel.text = identity.DeviceId;
        _regionLabel.text = string.IsNullOrEmpty(identity.Region) ? "global" : identity.Region;
        _projectKeyLabel.text = identity.ProjectKey;
      }

      RefreshWallets();
    }

    private void RefreshWallets()
    {
      var wallets = controller.Wallets;
      if (wallets == null || wallets.Count == 0)
      {
        _walletsLabel.text = "No wallets";
        return;
      }

      var builder = new StringBuilder();
      foreach (var wallet in wallets)
      {
        builder.AppendLine($"{wallet.Balance:0.##} {wallet.Currency}".TrimEnd());
      }
      _walletsLabel.text = builder.ToString().TrimEnd();
    }
  }
}
