using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class RemoteConfigPanel : MonoBehaviour
  {
    private const string FlashClass = "flash";
    private const long FlashMilliseconds = 600;

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

    private Label _playerSpeedValue;
    private Label _spawnIntervalValue;
    private Label _collectibleScoreValue;
    private Label _roundSecondsValue;
    private VisualElement _playerSpeedRow;
    private VisualElement _spawnIntervalRow;
    private VisualElement _collectibleScoreRow;
    private VisualElement _roundSecondsRow;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.TuningChanged += HandleTuningChanged;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.TuningChanged -= HandleTuningChanged;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _playerSpeedValue = root.Q<Label>("rc-value-player-speed");
      _spawnIntervalValue = root.Q<Label>("rc-value-spawn-interval");
      _collectibleScoreValue = root.Q<Label>("rc-value-collectible-score");
      _roundSecondsValue = root.Q<Label>("rc-value-round-seconds");
      _playerSpeedRow = root.Q("rc-row-player-speed");
      _spawnIntervalRow = root.Q("rc-row-spawn-interval");
      _collectibleScoreRow = root.Q("rc-row-collectible-score");
      _roundSecondsRow = root.Q("rc-row-round-seconds");

      Refresh();
    }

    private void Refresh()
    {
      var tuning = controller.Tuning;
      if (tuning == null)
      {
        return;
      }

      _playerSpeedValue.text = $"{Mathf.RoundToInt(tuning.PlayerSpeed)}";
      _spawnIntervalValue.text = $"{Mathf.RoundToInt(tuning.SpawnIntervalMs)} ms";
      _collectibleScoreValue.text = $"+{Mathf.RoundToInt(tuning.CollectibleScore)}";
      _roundSecondsValue.text = $"{Mathf.RoundToInt(tuning.RoundSeconds)} s";
    }

    private void HandleTuningChanged(string key)
    {
      Refresh();

      string normalized = key == null ? string.Empty : key.ToLowerInvariant().Replace("_", string.Empty).Replace("-", string.Empty).Replace(" ", string.Empty);
      if (normalized.Contains("playerspeed"))
      {
        Flash(_playerSpeedRow);
      }
      else if (normalized.Contains("spawninterval"))
      {
        Flash(_spawnIntervalRow);
      }
      else if (normalized.Contains("collectiblescore"))
      {
        Flash(_collectibleScoreRow);
      }
      else if (normalized.Contains("roundseconds"))
      {
        Flash(_roundSecondsRow);
      }
    }

    private static void Flash(VisualElement row)
    {
      row.AddToClassList(FlashClass);
      row.schedule.Execute(() => row.RemoveFromClassList(FlashClass)).StartingIn(FlashMilliseconds);
    }
  }
}
