using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using VirindiViewService.Controls;

namespace MosswartMassacre.Views
{
    /// <summary>
    /// Dedicated Flag Tracker window with comprehensive character tracking
    /// Ported from UBS Lua flagtracker with full functionality preservation
    /// </summary>
    internal class FlagTrackerView : VVSBaseView
    {
        private static FlagTrackerView instance;
        
        #region Tab Control References
        private HudTabView mainTabView;
        
        // Augmentations Tab
        private HudList lstAugmentations;
        private HudButton btnRefreshAugs;
        
        // Luminance Tab
        private HudList lstLuminanceAuras;
        private HudButton btnRefreshLum;
        
        // Recalls Tab
        private HudList lstRecallSpells;
        private HudButton btnRefreshRecalls;
        
        
        // Cantrips Tab
        private HudList lstCantrips;
        private HudButton btnRefreshCantrips;
        
        // Weapons Tab
        private HudList lstWeapons;
        private HudButton btnRefreshWeapons;
        
        // Quests Tab
        private HudList lstQuests;
        private HudButton btnRefreshQuests;
        
        #endregion

        #region Data Management
        private FlagTrackerData data;
        private QuestManager questManager;
        #endregion

        public FlagTrackerView(PluginCore core) : base(core)
        {
            instance = this;
            data = new FlagTrackerData();
            questManager = new QuestManager();
        }

        #region Static Interface
        public static void OpenFlagTracker()
        {
            try
            {
                if (instance == null)
                {
                    instance = new FlagTrackerView(null);
                    instance.InitializeView();
                }
                else
                {
                    // Bring existing window to front
                    if (instance.view != null)
                    {
                        instance.view.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error opening Flag Tracker: {ex.Message}");
            }
        }

        public static void CloseFlagTracker()
        {
            try
            {
                if (instance != null)
                {
                    instance.Dispose();
                    instance = null;
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error closing Flag Tracker: {ex.Message}");
            }
        }

        public static bool IsOpen()
        {
            return instance != null && instance.view != null && instance.view.Visible;
        }
        #endregion

        #region Initialization
        private void InitializeView()
        {
            try
            {
                // Create view from XML layout
                CreateFromXMLResource("MosswartMassacre.ViewXML.flagTracker.xml");

                // Initialize all tab controls
                InitializeTabControls();
                InitializeEventHandlers();

                // Initialize the base view
                Initialize();
                
                // Make the view visible
                if (view != null)
                {
                    view.Visible = true;
                    view.ShowInBar = true;
                    view.Title = "Mossy Tracker v3.0.1.1";
                }

                // Initial data refresh
                RefreshAllData();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error initializing Flag Tracker view: {ex.Message}");
            }
        }

        private void InitializeTabControls()
        {
            try
            {
                // Get main tab view
                mainTabView = GetControl<HudTabView>("mainTabView");
                
                // Augmentations Tab
                lstAugmentations = GetControl<HudList>("lstAugmentations");
                btnRefreshAugs = GetControl<HudButton>("btnRefreshAugs");
                
                // Luminance Tab
                lstLuminanceAuras = GetControl<HudList>("lstLuminanceAuras");
                btnRefreshLum = GetControl<HudButton>("btnRefreshLum");
                
                // Recalls Tab
                lstRecallSpells = GetControl<HudList>("lstRecallSpells");
                btnRefreshRecalls = GetControl<HudButton>("btnRefreshRecalls");
                
                // Cantrips Tab
                lstCantrips = GetControl<HudList>("lstCantrips");
                btnRefreshCantrips = GetControl<HudButton>("btnRefreshCantrips");
                
                // Weapons Tab
                lstWeapons = GetControl<HudList>("lstWeapons");
                btnRefreshWeapons = GetControl<HudButton>("btnRefreshWeapons");
                
                // Quests Tab
                lstQuests = GetControl<HudList>("lstQuests");
                btnRefreshQuests = GetControl<HudButton>("btnRefreshQuests");
                
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error initializing tab controls: {ex.Message}");
            }
        }

        private void InitializeEventHandlers()
        {
            try
            {
                // Refresh button events
                if (btnRefreshAugs != null) btnRefreshAugs.Hit += OnRefreshAugmentations;
                if (btnRefreshLum != null) btnRefreshLum.Hit += OnRefreshLuminance;
                if (btnRefreshRecalls != null) btnRefreshRecalls.Hit += OnRefreshRecalls;
                if (btnRefreshCantrips != null) btnRefreshCantrips.Hit += OnRefreshCantrips;
                if (btnRefreshWeapons != null) btnRefreshWeapons.Hit += OnRefreshWeapons;
                if (btnRefreshQuests != null) btnRefreshQuests.Hit += OnRefreshQuests;
                
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error initializing event handlers: {ex.Message}");
            }
        }
        #endregion

        #region Event Handlers
        private void OnRefreshAugmentations(object sender, EventArgs e)
        {
            try
            {
                data.RefreshAugmentations();
                PopulateAugmentationsList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing augmentations: {ex.Message}");
            }
        }

        private void OnRefreshLuminance(object sender, EventArgs e)
        {
            try
            {
                data.RefreshLuminanceAuras();
                PopulateLuminanceList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing luminance auras: {ex.Message}");
            }
        }

        private void OnRefreshRecalls(object sender, EventArgs e)
        {
            try
            {
                data.RefreshRecallSpells();
                PopulateRecallsList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing recall spells: {ex.Message}");
            }
        }


        private void OnRefreshCantrips(object sender, EventArgs e)
        {
            try
            {
                data.RefreshCantrips();
                PopulateCantripsList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing cantrips: {ex.Message}");
            }
        }

        private void OnRefreshWeapons(object sender, EventArgs e)
        {
            try
            {
                data.RefreshWeapons();
                PopulateWeaponsList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing weapons: {ex.Message}");
            }
        }

        private void OnRefreshQuests(object sender, EventArgs e)
        {
            try
            {
                questManager.RefreshQuests();
                PopulateQuestsList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing quests: {ex.Message}");
            }
        }

        #endregion

        #region Helper Methods
        private void SafeSetListText(HudList.HudListRowAccessor row, int columnIndex, string text)
        {
            try
            {
                if (row != null && columnIndex >= 0)
                {
                    // Check if the column exists
                    try
                    {
                        var control = row[columnIndex];
                        if (control != null)
                        {
                            ((HudStaticText)control).Text = text ?? "";
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        // Column doesn't exist - ignore silently
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error setting list text at column {columnIndex}: {ex.Message}");
            }
        }
        
        private void SafeSetListColor(HudList.HudListRowAccessor row, int columnIndex, Color color)
        {
            try
            {
                if (row != null && columnIndex >= 0 && row[columnIndex] != null)
                {
                    ((HudStaticText)row[columnIndex]).TextColor = color;
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error setting list color at column {columnIndex}: {ex.Message}");
            }
        }
        
        private void SafeSetListImage(HudList.HudListRowAccessor row, int columnIndex, int iconId)
        {
            try
            {
                if (row != null && columnIndex >= 0)
                {
                    try
                    {
                        var control = row[columnIndex];
                        
                        if (control != null && control is VirindiViewService.Controls.HudPictureBox)
                        {
                            var pictureBox = (VirindiViewService.Controls.HudPictureBox)control;
                            pictureBox.Image = iconId;
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        // Column doesn't exist - ignore silently
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error setting list image at column {columnIndex}: {ex.Message}");
            }
        }
        
        private string GetIconSymbol(string category)
        {
            switch (category)
            {
                case "Basic Recalls":
                    return "[B]"; // Basic recalls
                case "Island Recalls":
                    return "[I]"; // Island recalls
                case "Town Recalls": 
                    return "[T]"; // Town recalls
                case "Special Recalls":
                    return "[S]"; // Special recalls
                default:
                    return "[?]"; // Unknown category
            }
        }
        #endregion

        #region Data Population Methods
        private void RefreshAllData()
        {
            try
            {
                questManager.RefreshQuests();
                data.RefreshAll();
                
                PopulateAugmentationsList();
                PopulateLuminanceList();
                PopulateRecallsList();
                PopulateCantripsList();
                PopulateQuestsList();
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error refreshing all data: {ex.Message}");
            }
        }

        private void PopulateAugmentationsList()
        {
            try
            {
                if (lstAugmentations == null || data?.AugmentationCategories == null) return;
                
                lstAugmentations.ClearRows();
                
                foreach (var category in data.AugmentationCategories)
                {
                    // Add category header
                    var headerRow = lstAugmentations.AddRow();
                    SafeSetListText(headerRow, 0, $"--- {category.Key} ---");
                    SafeSetListText(headerRow, 1, "");
                    SafeSetListText(headerRow, 2, "");
                    SafeSetListText(headerRow, 3, "");
                    
                    // Add augmentations in this category
                    foreach (var aug in category.Value)
                    {
                        var row = lstAugmentations.AddRow();
                        
                        // Augmentation name with progress indicator
                        string progressText = aug.IsMaxed ? "[MAX]" : $"[{aug.CurrentValue}/{aug.Repeatable}]";
                        SafeSetListText(row, 0, aug.Name);
                        SafeSetListText(row, 1, progressText);
                        SafeSetListText(row, 2, aug.Trainer);
                        SafeSetListText(row, 3, aug.Location);
                        
                        // Color code based on completion status
                        Color progressColor = Color.Red;
                        if (aug.IsMaxed)
                        {
                            progressColor = Color.Green;
                        }
                        else if (aug.CurrentValue > 0)
                        {
                            progressColor = Color.Yellow;
                        }
                        
                        // Apply color to progress text
                        SafeSetListColor(row, 1, progressColor);
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error populating augmentations list: {ex.Message}");
            }
        }

        private void PopulateLuminanceList()
        {
            try
            {
                if (lstLuminanceAuras == null || data?.LuminanceAuraCategories == null) return;
                
                lstLuminanceAuras.ClearRows();
                
                foreach (var category in data.LuminanceAuraCategories)
                {
                    // Add category header
                    var headerRow = lstLuminanceAuras.AddRow();
                    SafeSetListText(headerRow, 0, $"--- {category.Key} ---");
                    SafeSetListText(headerRow, 1, "");
                    SafeSetListText(headerRow, 2, "");
                    
                    // Add luminance auras in this category
                    foreach (var aura in category.Value)
                    {
                        var row = lstLuminanceAuras.AddRow();
                        
                        // Aura name
                        SafeSetListText(row, 0, aura.Name);
                        
                        // Progress (current/cap)
                        string progressText = $"{aura.CurrentValue}/{aura.Cap}";
                        SafeSetListText(row, 1, progressText);
                        
                        // Category or quest flag for Seer auras
                        string categoryText = category.Key == "Seer Auras" && !string.IsNullOrEmpty(aura.QuestFlag) 
                            ? aura.QuestFlag 
                            : category.Key;
                        SafeSetListText(row, 2, categoryText);
                        
                        // Color code based on progress
                        Color progressColor = Color.Red;
                        if (aura.CurrentValue >= aura.Cap)
                        {
                            progressColor = Color.Green;
                        }
                        else if (aura.CurrentValue > 0)
                        {
                            progressColor = Color.Yellow;
                        }
                        
                        // Apply color to progress text
                        SafeSetListColor(row, 1, progressColor);
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error populating luminance list: {ex.Message}");
            }
        }

        private void PopulateRecallsList()
        {
            try
            {
                if (lstRecallSpells == null || data?.RecallSpells == null) return;
                
                lstRecallSpells.ClearRows();
                
                foreach (var recall in data.RecallSpells)
                {
                    var row = lstRecallSpells.AddRow();
                    
                    
                    // Column 0: Spell icon using MagTools approach
                    SafeSetListImage(row, 0, recall.IconId);
                    
                    // Column 1: Recall spell name
                    SafeSetListText(row, 1, recall.Name);
                    
                    // Column 2: Known status
                    string status = recall.IsKnown ? "Known" : "Unknown";
                    SafeSetListText(row, 2, status);
                    
                    // Color code based on known status
                    Color statusColor = recall.IsKnown ? Color.Green : Color.Red;
                    SafeSetListColor(row, 2, statusColor);
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error populating recalls list: {ex.Message}");
            }
        }


        private void PopulateCantripsList()
        {
            try
            {
                if (lstCantrips == null || data?.Cantrips == null) return;
                
                lstCantrips.ClearRows();
                
                foreach (var category in data.Cantrips)
                {
                    // Add category header
                    var headerRow = lstCantrips.AddRow();
                    SafeSetListImage(headerRow, 0, 0x6002856); // Star icon for category headers
                    SafeSetListText(headerRow, 1, $"--- {category.Key} ---");
                    SafeSetListText(headerRow, 2, "");
                    
                    // Add cantrips in this category
                    foreach (var cantrip in category.Value)
                    {
                        var row = lstCantrips.AddRow();
                        
                        // Column 0: Icon (green/red circle based on status)
                        SafeSetListImage(row, 0, cantrip.Value.ComputedIconId);
                        
                        // Column 1: Skill/Attribute name
                        SafeSetListText(row, 1, cantrip.Key);
                        
                        // Column 2: Cantrip level
                        SafeSetListText(row, 2, cantrip.Value.Value);
                        
                        // Apply color coding based on cantrip level
                        SafeSetListColor(row, 2, cantrip.Value.Color);
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error populating cantrips list: {ex.Message}");
            }
        }

        private void PopulateWeaponsList()
        {
            try
            {
                if (lstWeapons == null || data?.WeaponCategories == null) return;
                
                lstWeapons.ClearRows();
                
                foreach (var category in data.WeaponCategories)
                {
                    // Add category header
                    var headerRow = lstWeapons.AddRow();
                    SafeSetListText(headerRow, 0, $"--- {category.Key} ---");
                    SafeSetListText(headerRow, 1, "");
                    SafeSetListText(headerRow, 2, "");
                    SafeSetListText(headerRow, 3, "");
                    
                    // Add weapons in this category
                    foreach (var weapon in category.Value)
                    {
                        var row = lstWeapons.AddRow();
                        
                        // Column 0: Category
                        SafeSetListText(row, 0, weapon.Category);
                        
                        // Column 1: Weapon Type
                        SafeSetListText(row, 1, weapon.WeaponType);
                        
                        // Column 2: Weapon Name
                        SafeSetListText(row, 2, weapon.Name);
                        
                        // Column 3: Status
                        SafeSetListText(row, 3, weapon.Status);
                        
                        // Color code based on acquisition status
                        System.Drawing.Color statusColor = weapon.IsAcquired ? 
                            System.Drawing.Color.Green : System.Drawing.Color.Red;
                        SafeSetListColor(row, 3, statusColor);
                    }
                }
                
                if (data.WeaponCategories.Count == 0)
                {
                    var row = lstWeapons.AddRow();
                    SafeSetListText(row, 0, "No weapon data - click Refresh");
                    SafeSetListText(row, 1, "");
                    SafeSetListText(row, 2, "");
                    SafeSetListText(row, 3, "");
                    SafeSetListColor(row, 0, System.Drawing.Color.Gray);
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error populating weapons list: {ex.Message}");
            }
        }

        private void PopulateQuestsList()
        {
            try
            {
                if (lstQuests == null) 
                {
                    PluginCore.WriteToChat("Quest list control is null");
                    return;
                }
                
                lstQuests.ClearRows();
                
                // Always show debug info for now
                var row = lstQuests.AddRow();
                SafeSetListText(row, 0, $"Quest Manager: {(questManager != null ? "OK" : "NULL")}");
                SafeSetListText(row, 1, $"Quest Count: {questManager?.QuestList?.Count ?? 0}");
                SafeSetListText(row, 2, "Click Refresh to load quest data");
                SafeSetListText(row, 3, "");
                SafeSetListText(row, 4, "");
                SafeSetListText(row, 5, "");
                
                if (questManager?.QuestList != null && questManager.QuestList.Count > 0)
                {
                    foreach (var quest in questManager.QuestList.OrderBy(q => q.Id))
                    {
                        var questRow = lstQuests.AddRow();
                        
                        // Column 0: Quest Name
                        SafeSetListText(questRow, 0, quest.Id);
                        
                        // Column 1: Solves
                        SafeSetListText(questRow, 1, quest.Solves.ToString());
                        
                        // Column 2: Completed date
                        SafeSetListText(questRow, 2, questManager.FormatTimeStamp(quest.Timestamp));
                        
                        // Column 3: Max solves
                        string maxText = quest.MaxSolves < 0 ? "∞" : quest.MaxSolves.ToString();
                        SafeSetListText(questRow, 3, maxText);
                        
                        // Column 4: Delta (cooldown in seconds)
                        SafeSetListText(questRow, 4, questManager.FormatSeconds(quest.Delta));
                        
                        // Column 5: Expire time
                        string expireText = questManager.GetTimeUntilExpire(quest);
                        SafeSetListText(questRow, 5, expireText);
                        
                        // Color coding based on availability
                        var currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                        
                        if (quest.MaxSolves > 0 && quest.Solves >= quest.MaxSolves)
                        {
                            // Quest is maxed out - red
                            SafeSetListColor(questRow, 1, System.Drawing.Color.Red);
                            SafeSetListColor(questRow, 5, System.Drawing.Color.Red);
                        }
                        else if (quest.ExpireTime <= currentTime)
                        {
                            // Quest is available - green
                            SafeSetListColor(questRow, 5, System.Drawing.Color.Green);
                        }
                        else
                        {
                            // Quest is on cooldown - yellow
                            SafeSetListColor(questRow, 5, System.Drawing.Color.Yellow);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"Error populating quests list: {ex.Message}");
            }
        }
        #endregion


        #region Cleanup
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                try
                {
                    if (data != null)
                    {
                        data.Dispose();
                        data = null;
                    }
                    
                    if (questManager != null)
                    {
                        questManager.Dispose();
                        questManager = null;
                    }
                }
                catch (Exception ex)
                {
                    PluginCore.WriteToChat($"Error disposing Flag Tracker: {ex.Message}");
                }
            }
            
            base.Dispose(disposing);
        }
        #endregion
    }
}