using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using System;
using System.Diagnostics;
using System.Linq;

namespace Sonex.Client.Controls.DataGridView
{
    // Odpowiedzialnosc pliku: podmenu eksportu i uruchamianie scenariuszy eksportu z menu kontekstowego.
    public sealed partial class DataGridView
    {
        public void ShowExportMenu(FrameworkElement placementTarget)
        {
            var hasData = (_ItemsSourceFiltred?.Count ?? 0) > 0 && _Columns.Any(c => !c.IsHiden);
            var hasSelection = HasAnySelection();
            var menu = new MenuFlyout
            {
                MenuFlyoutPresenterStyle = GetContextMenuPresenterStyle()
            };

            menu.Items.Add(BuildExportSubMenu(selectionOnly: false, hasData: hasData, hasSelection: hasSelection));
            menu.Items.Add(BuildExportSubMenu(selectionOnly: true, hasData: hasData, hasSelection: hasSelection));
            menu.Opened += (_, _) => CursorDefault();
            menu.Closing += (_, _) => CursorDefault();
            menu.Closed += (_, _) => CursorDefault();
            menu.ShowAt(placementTarget, new FlyoutShowOptions
            {
                Placement = FlyoutPlacementMode.Bottom
            });
        }

        private MenuFlyoutSubItem BuildExportSubMenu(bool selectionOnly, bool hasData, bool hasSelection)
        {
            var subMenu = new MenuFlyoutSubItem
            {
                Text = selectionOnly ? "Export Selected" : "Export All",
                Icon = CreateContextMenuSvgIcon(selectionOnly ? "export_selected.svg" : "export_all.svg"),
                IsEnabled = selectionOnly ? hasData && hasSelection : hasData
            };
            AppendExportFormatItems(subMenu, selectionOnly);

            return subMenu;
        }

        private void AppendExportFormatItems(MenuFlyoutSubItem subMenu, bool selectionOnly)
        {
            subMenu.Items.Add(CreateExportMenuItem("CSV (.csv)", DataGridExportFormat.Csv, "csv.svg", selectionOnly: selectionOnly));
            subMenu.Items.Add(CreateExportMenuItem("Excel (.xlsx)", DataGridExportFormat.Xlsx, "excel.svg", selectionOnly: selectionOnly));
            subMenu.Items.Add(CreateExportMenuItem("Excel (.xlsx) without formatting", DataGridExportFormat.Xlsx, "excel.svg", xlsxWithFormatting: false, selectionOnly: selectionOnly));
            subMenu.Items.Add(CreateExportMenuItem("TSV (.tsv)", DataGridExportFormat.Tsv, "tsv.svg", selectionOnly: selectionOnly));
            subMenu.Items.Add(CreateExportMenuItem("HTML (.html)", DataGridExportFormat.Html, "html.svg", selectionOnly: selectionOnly));
        }

        private MenuFlyoutItem CreateExportMenuItem(string text, DataGridExportFormat format, string svgIconPath, bool xlsxWithFormatting = true, bool selectionOnly = false)
        {
            var item = new MenuFlyoutItem
            {
                Text = text,
                Icon = CreateContextMenuSvgIcon(svgIconPath)
            };

            item.Click += (_, _) => ExportFromContextMenu(format, xlsxWithFormatting, selectionOnly);
            return item;
        }

        private async void ExportFromContextMenu(DataGridExportFormat format, bool xlsxWithFormatting, bool selectionOnly)
        {
            try
            {
                var exportedPath = await ExportWithDialog(format, new DataGridExportOptions
                {
                    IncludeHeaders = true,
                    RowScope = selectionOnly ? DataGridExportRowScope.SelectedRows : DataGridExportRowScope.FilteredRows,
                    ColumnScope = selectionOnly ? DataGridExportColumnScope.SelectedColumns : DataGridExportColumnScope.VisibleColumns,
                    FallbackToFilteredRowsWhenNoSelection = selectionOnly,
                    FallbackToVisibleColumnsWhenNoSelection = selectionOnly,
                    XlsxUseFormatting = xlsxWithFormatting
                });
                OpenExportedFile(exportedPath);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[DataGridView] Export failed: {ex}");
            }
        }

        private static void OpenExportedFile(string? filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath) || !System.IO.File.Exists(filePath))
            {
                return;
            }

            try
            {
                Process.Start(new ProcessStartInfo
                {
                    FileName = filePath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[DataGridView] Export open file failed: {ex}");
            }
        }
    }
}
