using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class PM5TestUI : MonoBehaviour
{
    [Header("UI References")]
    [SerializeField] private TMP_Text wattsText;
    [SerializeField] private TMP_Text spmText;
    [SerializeField] private TMP_Text distanceText;
    [SerializeField] private TMP_Text hrText;      // NEW
    [SerializeField] private TMP_Text caloriesText; // NEW
    [SerializeField] private TMP_Text statusText;
    [SerializeField] private Image statusIndicator; 
    [SerializeField] private Button connectButton;

    [Header("Logging")]
    [SerializeField] private Transform logContent;
    [SerializeField] private GameObject logItemPrefab;

    private void Start()
    {
        if (PerformanceMonitorManager.Instance != null)
        {
            PerformanceMonitorManager.Instance.OnLog += AddLog;
            PerformanceMonitorManager.Instance.OnConnectionStateChanged += UpdateStatusUI;
            PerformanceMonitorManager.Instance.OnStatsUpdated += UpdateDashboard;
        }

        connectButton.onClick.AddListener(() => {
            PerformanceMonitorManager.Instance.StartScan();
        });

        UpdateStatusUI(false);
    }

    private void UpdateDashboard(PerformanceMonitorManager.RowingStats stats)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() => {
            if (wattsText) wattsText.text = $"{stats.Watts} W";
            if (spmText) spmText.text = $"{stats.SPM} s/m";
            if (distanceText) distanceText.text = $"{stats.Distance:F0} m";
            
            if (hrText) hrText.text = stats.HeartRate > 0 ? $"{stats.HeartRate} bpm" : "--";
            if (caloriesText) caloriesText.text = $"{stats.Calories} cal";
        });
    }

    private void UpdateStatusUI(bool isConnected)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() => {
            if (statusText)
            {
                statusText.text = isConnected ? "CONNECTED" : "DISCONNECTED";
                statusText.color = isConnected ? Color.green : Color.red;
            }

            if (statusIndicator)
                statusIndicator.color = isConnected ? Color.green : Color.red;

            if (connectButton)
                connectButton.interactable = !isConnected;
        });
    }

    private void AddLog(string message)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() => {
            if (logContent == null || logItemPrefab == null) return;

            // Optional: Limit log size to prevent lag
            if (logContent.childCount > 20) 
                Destroy(logContent.GetChild(0).gameObject);

            GameObject newItem = Instantiate(logItemPrefab, logContent);
            TMP_Text txt = newItem.GetComponent<TMP_Text>();
            if (txt) txt.text = $"[{System.DateTime.Now:HH:mm:ss}] {message}";
            
            Canvas.ForceUpdateCanvases();
            ScrollRect sr = logContent.GetComponentInParent<ScrollRect>();
            if (sr) sr.verticalNormalizedPosition = 0f;
        });
    }
}