using System;
using System.Collections.Generic;
using System.Linq;
using eagle.Notifications;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace eagle {
    using ProvinceId = Int32;

    public class NotificationPanel : PopupPanelController {
        public Button dismissAllButton;
        public TMP_Text dismissOneButtonText;
        public GameObject spacer;

        private readonly Queue<Notification> _notes = new();

        private void SetPopupInfos() {
            PopupInfos = _notes.Select(note => new PopupInfo {
                                   titleText = note.Title,
                                   mainText = note.Text,
                                   mainTextLlmId = note.LlmId,
                                   affectedProvinceIds = note.ProvinceIds,
                                   displayedHeroes = note.DisplayedHeroes
                               })
                                 .ToList();

            SetUpPanel();

            // If there are no images, add a spacer to the panel
            spacer.gameObject.SetActive(!imagesAndNamesContainer.gameObject.activeSelf);
            if (PopupInfos.Count == 1) {
                dismissAllButton.gameObject.SetActive(false);
                dismissOneButtonText.text = "Done";
            } else {
                dismissAllButton.gameObject.SetActive(true);
                dismissOneButtonText.text = "Dismiss";
            }
        }

        public void AddNote(
                string title,
                string text,
                string llmId,
                List<ProvinceId> provinceIds,
                List<HeroView> displayedHeroes) {
            MainQueue.Q.Enqueue(() => {
                var existingNote = _notes.FirstOrDefault(
                        n => n.Title == title && n.DisplayedHeroes.SequenceEqual(displayedHeroes));

                if (existingNote == null) {
                    _notes.Enqueue(new Notification(
                            title: title,
                            text: text,
                            llmId: llmId,
                            provinceIds: provinceIds,
                            displayedHeroes: displayedHeroes));
                } else {
                    existingNote.Append(text, provinceIds);
                }
                SetPopupInfos();
            });
        }

        public void DismissButtonClicked() {
            _notes.Dequeue();
            SetPopupInfos();
        }

        public void DismissAllClicked() {
            _notes.Clear();
            SetPopupInfos();
        }
    }
}