using System;
using Unity.Netcode;
using TMPro;
using UnityEngine;

public class SynchronizedTimer : NetworkBehaviour
{
    public event Action OnTimerEnd;

    [SerializeField] private TextMeshProUGUI timerText;

    private NetworkVariable<float> timer = new NetworkVariable<float>(
        0f,
        NetworkVariableReadPermission.Everyone,
        NetworkVariableWritePermission.Server
    );

    private bool isTimerRunning = false;
    private void Start()
    {
        timerText.gameObject.SetActive( false );
    }
    private void Update()
    {
        if (IsServer && isTimerRunning)
        {
            timer.Value -= Time.deltaTime;
            if (timer.Value <= 0)
            {
                timer.Value = 0;
                isTimerRunning = false;
                OnTimerEnd?.Invoke();
            }
        UpdateTimerUI();
        }

    }

    public void StartTimerServer(float time)
    {
        if (!isTimerRunning && time > 0)
        {
            timer.Value = time;
            isTimerRunning = true;
            timerTextEnablerClientRpc();
        }
    }
    [ClientRpc]
    void timerTextEnablerClientRpc()
    {
            timerText.gameObject.SetActive ( true );

    }

    public float GetRemainingTime()
    {
        return timer.Value;
    }

    private void OnEnable()
    {
        timer.OnValueChanged += OnTimerValueChanged;
    }

    private void OnDisable()
    {
        timer.OnValueChanged -= OnTimerValueChanged;
    }

    private void OnTimerValueChanged(float oldValue, float newValue)
    {
        if (newValue <= 0 && oldValue > 0)
        {
            OnTimerEnd?.Invoke();
        }
        UpdateTimerUI();
    }

    private void UpdateTimerUI()
    {
        if (timerText != null)
        {
            int minutes = Mathf.FloorToInt(timer.Value / 60);
            int seconds = Mathf.FloorToInt(timer.Value % 60);
            timerText.text = $"{minutes:D2}:{seconds:D2}";
        }
    }
}