/*
 * Copyright (c) 2026 Erik Darling, Darling Data LLC
 *
 * This file is part of the SQL Server Performance Monitor.
 *
 * Licensed under the MIT License. See LICENSE file in the project root for full license information.
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Microsoft.Win32;
using PerformanceMonitorDashboard.Helpers;
using PerformanceMonitorDashboard.Models;
using PerformanceMonitorDashboard.Services;
using ScottPlot;
using PerformanceMonitor.Ui;
using PerformanceMonitor.Common;

namespace PerformanceMonitorDashboard
{
    public partial class TracePatternHistoryWindow : Window
    {
        private readonly DatabaseService _databaseService;
        private readonly string _databaseName;
        private readonly string _queryPattern;
        private readonly int _hoursBack;
        private readonly DateTime? _fromDate;
        private readonly DateTime? _toDate;
        private readonly PlanNavigationController _planActions;
        private List<TracePatternDetailItem> _historyData = new();
        private ChartHoverHelper? _chartHover;

        // Filter state
        private Dictionary<string, ColumnFilterState> _filters = new();
        private List<TracePatternDetailItem>? _unfilteredData;
        private Popup? _filterPopup;
        private ColumnFilterPopup? _filterPopupContent;

        public TracePatternHistoryWindow(
            DatabaseService databaseService,
            string databaseName,
            string queryPattern,
            int hoursBack = 24,
            DateTime? fromDate = null,
            DateTime? toDate = null)
        {
            InitializeComponent();

            _databaseService = databaseService;
            _databaseName = databaseName;
            _queryPattern = queryPattern;
            _hoursBack = hoursBack;
            _fromDate = fromDate;
            _toDate = toDate;

            _planActions = new PlanNavigationController(
                this,
                (xml, label, qt) => PlanViewerWindow.ShowPlanAsync(this, xml, label, qt),
                (db, qt, est, iso, ct) => ActualPlanExecutor.ExecuteForActualPlanAsync(
                    _databaseService.ConnectionString, db, qt, est, iso, isAzureSqlDb: false, timeoutSeconds: 0, ct),
                "the monitored server");

            // Collapse newlines/tabs to spaces and truncate for a clean single-line header
            var displayPattern = MultipleSpacesRegExp().Replace(queryPattern, " ").Trim();
            if (displayPattern.Length > 120)
                displayPattern = displayPattern.Substring(0, 120) + "...";
            QueryIdentifierText.Text = $"Trace Pattern History: [{databaseName}] — {displayPattern}";

            ApplyThemeToChart();
            Loaded += TracePatternHistoryWindow_Loaded;
            ThemeManager.ThemeChanged += OnThemeChanged;
            Closed += (s, e) => ThemeManager.ThemeChanged -= OnThemeChanged;
        }

        private void ApplyThemeToChart()
        {
            Helpers.TabHelpers.ApplyThemeToChart(HistoryChart);
        }

        private void OnThemeChanged(string _)
        {
            ApplyThemeToChart();
            HistoryChart.Refresh();
        }

        private async void TracePatternHistoryWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                await LoadHistoryAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    $"Failed to load trace pattern history:\n\n{ex.Message}",
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error
                );
            }
        }

        private async Task LoadHistoryAsync()
        {
            try
            {
                _historyData = await _databaseService.GetTracePatternHistoryAsync(_databaseName, _queryPattern, _hoursBack, _fromDate, _toDate);

                _unfilteredData = _historyData;
                _filters.Clear();
                HistoryDataGrid.ItemsSource = _historyData;
                UpdateFilterButtonStyles();

                if (_historyData.Count > 0)
                {
                    var avgDuration = _historyData.Where(h => h.DurationMs.HasValue).Select(h => (double)(h.DurationMs ?? 0)).DefaultIfEmpty(0).Average();
                    var avgCpu = _historyData.Where(h => h.CpuMs.HasValue).Select(h => (double)(h.CpuMs ?? 0)).DefaultIfEmpty(0).Average();
                    var firstSample = _historyData.Where(h => h.EndTime.HasValue).Min(h => h.EndTime);
                    var lastSample = _historyData.Where(h => h.EndTime.HasValue).Max(h => h.EndTime);

                    SummaryText.Text = string.Format(CultureInfo.CurrentCulture,
                        "Executions: {0} | First: {1:yyyy-MM-dd HH:mm} | Last: {2:yyyy-MM-dd HH:mm} | Avg Duration: {3:N0} ms | Avg CPU: {4:N0} ms",
                        _historyData.Count, firstSample, lastSample, avgDuration, avgCpu);

                    UpdateChart();
                }
                else
                {
                    SummaryText.Text = "No historical data found for this pattern.";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    $"Failed to load trace pattern history:\n\n{ex.Message}",
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error
                );
            }
        }

        private void MetricSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_historyData.Count > 0)
            {
                UpdateChart();
            }
        }

        private void UpdateChart()
        {
            if (_historyData == null || _historyData.Count == 0)
                return;

            HistoryChart.Plot.Clear();

            var selectedItem = MetricSelector.SelectedItem as ComboBoxItem;
            var metricTag = selectedItem?.Tag?.ToString() ?? "DurationMs";
            var metricLabel = selectedItem?.Content?.ToString() ?? "Duration (ms)";

            var orderedData = _historyData
                .Where(h => h.EndTime.HasValue)
                .OrderBy(h => h.EndTime)
                .ToList();

            if (orderedData.Count == 0) return;

            var dates = orderedData.Select(h => h.EndTime!.Value.ToOADate()).ToArray();
            var values = orderedData.Select(h => GetMetricValue(h, metricTag)).ToArray();

            var color = ScottPlot.Color.FromHex(ChartPalette.SeriesColor("MetricTrend"));
            var scatter = HistoryChart.Plot.Add.Scatter(dates, values);
            scatter.Color = color;
            ChartStyle.StyleScatter(scatter);

            HistoryChart.Plot.Axes.DateTimeTicksBottomDateChange();
            Helpers.TabHelpers.ReapplyAxisColors(HistoryChart);
            HistoryChart.Plot.YLabel(metricLabel);
            HistoryChart.Plot.XLabel("End Time");

            // Hover tooltip
            var unit = metricTag.Contains("Ms") ? "ms" : "";
            if (_chartHover == null)
                _chartHover = new ChartHoverHelper(HistoryChart, unit);
            else
                _chartHover.Unit = unit;
            _chartHover.Clear();
            _chartHover.Add(scatter, metricLabel);

            HistoryChart.Refresh();
        }

        private static double GetMetricValue(TracePatternDetailItem item, string metricTag)
        {
            return metricTag switch
            {
                "DurationMs" => (double)(item.DurationMs ?? 0),
                "CpuMs" => (double)(item.CpuMs ?? 0),
                "Reads" => (double)(item.Reads ?? 0),
                "Writes" => (double)(item.Writes ?? 0),
                "RowCounts" => (double)(item.RowCounts ?? 0),
                _ => (double)(item.DurationMs ?? 0)
            };
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        #region Column Filter Popup

        private void Filter_Click(object sender, RoutedEventArgs e)
        {
            if (sender is not Button button || button.Tag is not string columnName) return;

            if (_filterPopup == null)
            {
                _filterPopupContent = new ColumnFilterPopup();
                _filterPopupContent.FilterApplied += FilterPopup_FilterApplied;
                _filterPopupContent.FilterCleared += FilterPopup_FilterCleared;

                _filterPopup = new Popup
                {
                    Child = _filterPopupContent,
                    StaysOpen = false,
                    Placement = PlacementMode.Bottom,
                    AllowsTransparency = true
                };
            }

            _filters.TryGetValue(columnName, out var existingFilter);
            _filterPopupContent!.Initialize(columnName, existingFilter);

            _filterPopup.PlacementTarget = button;
            _filterPopup.IsOpen = true;
        }

        private void FilterPopup_FilterApplied(object? sender, FilterAppliedEventArgs e)
        {
            if (_filterPopup != null) _filterPopup.IsOpen = false;

            if (e.FilterState.IsActive)
                _filters[e.FilterState.ColumnName] = e.FilterState;
            else
                _filters.Remove(e.FilterState.ColumnName);

            ApplyFilters();
            UpdateFilterButtonStyles();
        }

        private void FilterPopup_FilterCleared(object? sender, EventArgs e)
        {
            if (_filterPopup != null) _filterPopup.IsOpen = false;
        }

        private void ApplyFilters()
        {
            if (_unfilteredData == null) return;

            if (_filters.Count == 0)
            {
                HistoryDataGrid.ItemsSource = _unfilteredData;
                return;
            }

            var filtered = _unfilteredData.Where(item =>
            {
                foreach (var filter in _filters.Values)
                {
                    if (filter.IsActive && !DataGridFilterService.MatchesFilter(item, filter))
                        return false;
                }
                return true;
            }).ToList();

            HistoryDataGrid.ItemsSource = filtered;
        }

        private void UpdateFilterButtonStyles()
        {
            foreach (var column in HistoryDataGrid.Columns)
            {
                if (column.Header is StackPanel stackPanel)
                {
                    var filterButton = stackPanel.Children.OfType<Button>().FirstOrDefault();
                    if (filterButton?.Tag is string columnName)
                    {
                        bool hasActive = _filters.TryGetValue(columnName, out var filter) && filter.IsActive;
                        filterButton.Content = new System.Windows.Controls.TextBlock
                        {
                            Text = "\uE71C",
                            FontFamily = new System.Windows.Media.FontFamily("Segoe MDL2 Assets"),
                            Foreground = hasActive
                                ? new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xD7, 0x00))
                                : new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF))
                        };
                        filterButton.ToolTip = hasActive && filter != null
                            ? $"Filter: {filter.DisplayText}\n(Click to modify)"
                            : "Click to filter";
                    }
                }
            }
        }

        #endregion

        #region Context Menu Handlers

        private void CopyCell_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem && menuItem.Parent is ContextMenu contextMenu)
            {
                var dataGrid = TabHelpers.FindDataGridFromContextMenu(contextMenu);
                if (dataGrid != null && dataGrid.CurrentCell.Item != null)
                {
                    var cellContent = TabHelpers.GetCellContent(dataGrid, dataGrid.CurrentCell);
                    if (!string.IsNullOrEmpty(cellContent))
                        Clipboard.SetDataObject(cellContent, false);
                }
            }
        }

        private void CopyRow_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem && menuItem.Parent is ContextMenu contextMenu)
            {
                var dataGrid = TabHelpers.FindDataGridFromContextMenu(contextMenu);
                if (dataGrid?.SelectedItem != null)
                    Clipboard.SetDataObject(TabHelpers.GetRowAsText(dataGrid, dataGrid.SelectedItem), false);
            }
        }

        private void CopyAllRows_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem && menuItem.Parent is ContextMenu contextMenu)
            {
                var dataGrid = TabHelpers.FindDataGridFromContextMenu(contextMenu);
                if (dataGrid != null && dataGrid.Items.Count > 0)
                {
                    var sb = new StringBuilder();
                    var headers = new List<string>();
                    foreach (var column in dataGrid.Columns)
                    {
                        if (column is DataGridBoundColumn)
                            headers.Add(DataGridClipboardBehavior.GetHeaderText(column));
                    }
                    sb.AppendLine(string.Join("\t", headers));
                    foreach (var item in dataGrid.Items)
                        sb.AppendLine(TabHelpers.GetRowAsText(dataGrid, item));
                    Clipboard.SetDataObject(sb.ToString(), false);
                }
            }
        }

        private void ExportToCsv_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem && menuItem.Parent is ContextMenu contextMenu)
            {
                var dataGrid = TabHelpers.FindDataGridFromContextMenu(contextMenu);
                if (dataGrid != null && dataGrid.Items.Count > 0)
                {
                    var saveFileDialog = new SaveFileDialog
                    {
                        FileName = $"trace_pattern_history_{DateTime.Now:yyyyMMdd_HHmmss}.csv",
                        DefaultExt = ".csv",
                        Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"
                    };

                    if (saveFileDialog.ShowDialog() == true)
                    {
                        try
                        {
                            var sb = new StringBuilder();
                            var headers = new List<string>();
                            foreach (var column in dataGrid.Columns)
                            {
                                if (column is DataGridBoundColumn)
                                    headers.Add(TabHelpers.EscapeCsvField(DataGridClipboardBehavior.GetHeaderText(column)));
                            }
                            sb.AppendLine(string.Join(",", headers));
                            foreach (var item in dataGrid.Items)
                            {
                                var values = TabHelpers.GetRowValues(dataGrid, item);
                                sb.AppendLine(string.Join(",", values.Select(v => TabHelpers.EscapeCsvField(v))));
                            }
                            File.WriteAllText(saveFileDialog.FileName, sb.ToString());
                            MessageBox.Show($"Data exported successfully to:\n{saveFileDialog.FileName}", "Export Complete", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Error exporting data:\n\n{ex.Message}", "Export Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
        }

        [System.Text.RegularExpressions.GeneratedRegex(@"\s+")]
        private static partial System.Text.RegularExpressions.Regex MultipleSpacesRegExp();

        #endregion

        #region Plan Actions

        // Trace patterns are aggregated trace/RPC-completed events with no cached plan, so only
        // "Get Actual Plan" is offered (re-execute the sampled statement) — mirroring how the main
        // grid treats LongRunningQueryPatternItem.
        private async void GetActualPlan_Click(object sender, RoutedEventArgs e)
        {
            if (GetHistoryItem(sender) is not { } item) return;
            await _planActions.GetActualPlanAsync(item.SqlText, _databaseName, "Actual Plan - Trace Pattern");
        }

        private static TracePatternDetailItem? GetHistoryItem(object sender)
        {
            if (sender is MenuItem menuItem && menuItem.Parent is ContextMenu contextMenu)
            {
                var dataGrid = TabHelpers.FindDataGridFromContextMenu(contextMenu);
                return (dataGrid?.CurrentCell.Item ?? dataGrid?.SelectedItem) as TracePatternDetailItem;
            }
            return null;
        }

        #endregion
    }
}
