using UnityEngine;
using UnityEngine.UI;
using EventsAppQuest.Web.Application;

namespace EventsAppQuest.Web.Presentation
{
    /// <summary>
    /// Lista mock de tarefas de follow-up (camada Web).
    /// </summary>
    public class FollowUpTaskView : MonoBehaviour, IWebContentRoot
    {
        private Transform _content;

        public void SetContentRoot(Transform contentRoot) => _content = contentRoot;

        private void Start()
        {
            Refresh();
            WebRuntimeContext.OnDataChanged += Refresh;
        }
        private void OnDestroy() => WebRuntimeContext.OnDataChanged -= Refresh;

        public void Refresh()
        {
            if (_content == null) return;
            ClearContent(_content);
            var service = WebRuntimeContext.DataService;
            if (service == null) return;
            var font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            foreach (var task in service.GetFollowUpTasks())
            {
                var go = new GameObject("TaskRow");
                go.transform.SetParent(_content, false);
                var rt = go.AddComponent<RectTransform>();
                rt.sizeDelta = new Vector2(0, 22);
                var text = go.AddComponent<Text>();
                var due = task.DueDate.HasValue ? task.DueDate.Value.ToString("d") : "-";
                text.text = $"[{task.Priority}] {task.Title} | Due: {due} | {(task.IsCompleted ? "Done" : "Open")}";
                text.font = font;
                text.fontSize = 14;
            }
        }

        private void ClearContent(Transform content)
        {
            for (var i = content.childCount - 1; i >= 0; i--)
                Destroy(content.GetChild(i).gameObject);
        }
    }
}
