using System;
using System.Collections.Generic;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;

namespace eagle {
    public class DynamicFactionTextUpdater : IDisposable {
        private List<GeneratedTextListener> textListeners = new();
        private Dictionary<string, TMP_Text> textComponents = new();
        private Dictionary<string, FactionTextConfig> factionConfigs = new();

        private class FactionTextConfig {
            public FactionView Faction { get; }
            public IGameModel GameModel { get; }
            public string Template { get; }
            public string FallbackText { get; }

            public FactionTextConfig(
                    FactionView faction,
                    IGameModel gameModel,
                    string template,
                    string fallbackText) {
                Faction = faction;
                GameModel = gameModel;
                Template = template;
                FallbackText = fallbackText;
            }
        }

        public void SetFactionText(
                TMP_Text textComponent,
                FactionView faction,
                IGameModel gameModel,
                string template = null,
                string fallbackText = null) {
            if (!textComponent || faction == null || gameModel == null) return;

            string componentKey = textComponent.GetEntityId().ToString();
            textComponents[componentKey] = textComponent;

            // Use the provided template or get the default faction string template
            string actualTemplate =
                    template ?? DisplayNames.FactionStringTemplate(faction, gameModel);
            string actualFallback = fallbackText ?? faction.Name;

            factionConfigs[componentKey] =
                    new FactionTextConfig(faction, gameModel, actualTemplate, actualFallback);

            // Set initial text
            UpdateFactionText(componentKey);

            var factionLeaderName = DynamicTextTemplate.Placeholder(
                    DisplayNames.FactionTextPlaceholders.FactionLeaderName);
            if (actualTemplate.Contains(factionLeaderName)) {
                var leader = gameModel.Heroes[faction.FactionHeadId];
                if (!string.IsNullOrEmpty(leader.NameTextId)) {
                    var textEntry = ClientTextProvider.Provider.GetTextEntry(leader.NameTextId);
                    if (textEntry == null || string.IsNullOrEmpty(textEntry.Text)) {
                        // Create listener for dynamic updates
                        var listener = new GeneratedTextListener(
                                leader.NameTextId,
                                "",
                                "",
                                0,
                                (index, text) => UpdateFactionText(componentKey));

                        textListeners.Add(listener);
                        ClientTextProvider.Provider.AddListener(listener);
                    }
                }
            }
        }

        public void SetFactionTextWithCustomFormat(
                TMP_Text textComponent,
                FactionView faction,
                IGameModel gameModel,
                string customFormat,
                string fallbackText = null) {
            if (!textComponent || faction == null || gameModel == null ||
                string.IsNullOrEmpty(customFormat))
                return;

            string componentKey = textComponent.GetEntityId().ToString();
            textComponents[componentKey] = textComponent;

            string actualFallback = fallbackText ?? faction.Name;
            factionConfigs[componentKey] =
                    new FactionTextConfig(faction, gameModel, customFormat, actualFallback);

            // Set initial text
            UpdateFactionTextWithCustomFormat(componentKey, customFormat);

            var factionLeaderName = DynamicTextTemplate.Placeholder(
                    DisplayNames.FactionTextPlaceholders.FactionLeaderName);
            if (customFormat.Contains(factionLeaderName)) {
                var leader = gameModel.Heroes[faction.FactionHeadId];
                if (!string.IsNullOrEmpty(leader.NameTextId)) {
                    var textEntry = ClientTextProvider.Provider.GetTextEntry(leader.NameTextId);
                    if (textEntry == null || string.IsNullOrEmpty(textEntry.Text)) {
                        // Create listener for dynamic updates
                        var listener = new GeneratedTextListener(
                                leader.NameTextId,
                                "",
                                "",
                                0,
                                (index, text) => UpdateFactionTextWithCustomFormat(
                                        componentKey,
                                        customFormat));

                        textListeners.Add(listener);
                        ClientTextProvider.Provider.AddListener(listener);
                    }
                }
            }
        }

        private void UpdateFactionText(string componentKey) {
            if (!textComponents.TryGetValue(componentKey, out var component) ||
                !factionConfigs.TryGetValue(componentKey, out var config) || component == null) {
                return;
            }

            var template = config.Template;
            var factionLeaderName = DynamicTextTemplate.Placeholder(
                    DisplayNames.FactionTextPlaceholders.FactionLeaderName);
            if (template.Contains(factionLeaderName)) {
                var leader = config.GameModel.Heroes[config.Faction.FactionHeadId];
                var textEntry = ClientTextProvider.Provider.GetTextEntry(leader.NameTextId);
                if (textEntry != null && !string.IsNullOrEmpty(textEntry.Text)) {
                    component.text = template.Replace(factionLeaderName, textEntry.Text);
                } else {
                    component.text = template.Replace(factionLeaderName, "Leader");
                }
            } else {
                component.text = template;
            }
        }

        private void UpdateFactionTextWithCustomFormat(string componentKey, string customFormat) {
            if (!textComponents.TryGetValue(componentKey, out var component) ||
                !factionConfigs.TryGetValue(componentKey, out var config) || component == null) {
                return;
            }

            string resolvedText = customFormat;
            var factionLeaderName = DynamicTextTemplate.Placeholder(
                    DisplayNames.FactionTextPlaceholders.FactionLeaderName);
            if (customFormat.Contains(factionLeaderName)) {
                var leader = config.GameModel.Heroes[config.Faction.FactionHeadId];
                var textEntry = ClientTextProvider.Provider.GetTextEntry(leader.NameTextId);
                if (textEntry != null && !string.IsNullOrEmpty(textEntry.Text)) {
                    resolvedText = resolvedText.Replace(factionLeaderName, textEntry.Text);
                } else {
                    resolvedText = resolvedText.Replace(factionLeaderName, "Leader");
                }
            }

            var factionName = DynamicTextTemplate.Placeholder(
                    DisplayNames.FactionTextPlaceholders.FactionName);
            if (customFormat.Contains(factionName)) {
                resolvedText = resolvedText.Replace(factionName, config.Faction.Name);
            }

            var prestige =
                    DynamicTextTemplate.Placeholder(DisplayNames.FactionTextPlaceholders.Prestige);
            if (customFormat.Contains(prestige)) {
                resolvedText = resolvedText.Replace(prestige, config.Faction.Prestige.ToString());
            }

            component.text = resolvedText;
        }

        public void Dispose() {
            foreach (var listener in textListeners) {
                ClientTextProvider.Provider.RemoveListener(listener);
            }
            textListeners.Clear();
            textComponents.Clear();
            factionConfigs.Clear();
        }
    }
}
