using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using MusicBeePlugin.Clouseau.Core;
using MusicBeePlugin.Clouseau.Logging;
using MusicBeePlugin.Clouseau.Metrics;
using NLog;

namespace MusicBeePlugin.Clouseau.UI
{
    /// <summary>
    /// UI Gallery form that displays thumbnails and live previews of all Clouseau UI components.
    /// Provides screenshot capture functionality for documentation and debugging.
    /// </summary>
    public class UIGalleryForm : Form
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // Dark theme colors (consistent with DashboardForm)
        private static readonly Color DarkBackground = Color.FromArgb(30, 30, 30);
        private static readonly Color DarkPanel = Color.FromArgb(45, 45, 48);
        private static readonly Color DarkBorder = Color.FromArgb(67, 67, 70);
        private static readonly Color DarkText = Color.FromArgb(241, 241, 241);
        private static readonly Color DarkTextDim = Color.FromArgb(153, 153, 153);
        private static readonly Color DarkAccent = Color.FromArgb(0, 122, 204);
        private static readonly Color DarkHover = Color.FromArgb(62, 62, 64);
        private static readonly Color StatusOpen = Color.FromArgb(76, 175, 80);
        private static readonly Color StatusClosed = Color.FromArgb(158, 158, 158);

        // UI Components
        private FlowLayoutPanel _galleryPanel;
        private Panel _toolbarPanel;
        private Button _captureAllButton;
        private Button _refreshButton;
        private Button _openFolderButton;
        private Label _statusLabel;
        private Timer _refreshTimer;

        // Gallery item size
        private const int ThumbnailWidth = 220;
        private const int ThumbnailHeight = 165;
        private const int ItemPanelWidth = 240;
        private const int ItemPanelHeight = 280;

        // Dependencies
        private readonly Plugin.MusicBeeApiInterface _mbApi;
        private readonly string _dataPath;
        private readonly string _pluginsPath;
        private readonly ClouseauSettings _settings;
        private readonly StateManager _stateManager;
        private readonly MetricsCollector _metricsCollector;
        private readonly EventLogger _eventLogger;

        // Tracked forms
        private readonly List<GalleryItem> _galleryItems;

        /// <summary>
        /// Creates a new UIGalleryForm.
        /// </summary>
        public UIGalleryForm(
            Plugin.MusicBeeApiInterface mbApi,
            string dataPath,
            string pluginsPath,
            ClouseauSettings settings = null,
            StateManager stateManager = null,
            MetricsCollector metricsCollector = null,
            EventLogger eventLogger = null)
        {
            _mbApi = mbApi;
            _dataPath = dataPath;
            _pluginsPath = pluginsPath;
            _settings = settings ?? new ClouseauSettings();
            _stateManager = stateManager;
            _metricsCollector = metricsCollector;
            _eventLogger = eventLogger;
            _galleryItems = new List<GalleryItem>();

            InitializeForm();
            InitializeToolbar();
            InitializeGalleryPanel();
            PopulateGalleryItems();
            StartRefreshTimer();
        }

        /// <summary>
        /// Initializes the form properties.
        /// </summary>
        private void InitializeForm()
        {
            Text = "Clouseau UI Gallery";
            Size = new Size(800, 650);
            MinimumSize = new Size(600, 450);
            StartPosition = FormStartPosition.CenterScreen;
            BackColor = DarkBackground;
            ForeColor = DarkText;
            Font = new Font("Segoe UI", 9f);
            FormBorderStyle = FormBorderStyle.Sizable;
            Icon = null;
        }

        /// <summary>
        /// Initializes the toolbar panel with action buttons.
        /// </summary>
        private void InitializeToolbar()
        {
            _toolbarPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 50,
                BackColor = DarkPanel,
                Padding = new Padding(10, 8, 10, 8)
            };

            // Capture All button
            _captureAllButton = CreateDarkButton("Capture All", DarkAccent);
            _captureAllButton.Location = new Point(10, 10);
            _captureAllButton.Size = new Size(100, 30);
            _captureAllButton.Click += OnCaptureAllClick;
            _toolbarPanel.Controls.Add(_captureAllButton);

            // Refresh button
            _refreshButton = CreateDarkButton("Refresh", DarkPanel);
            _refreshButton.Location = new Point(120, 10);
            _refreshButton.Size = new Size(80, 30);
            _refreshButton.Click += OnRefreshClick;
            _toolbarPanel.Controls.Add(_refreshButton);

            // Open Folder button
            _openFolderButton = CreateDarkButton("Open Screenshots", DarkPanel);
            _openFolderButton.Location = new Point(210, 10);
            _openFolderButton.Size = new Size(120, 30);
            _openFolderButton.Click += OnOpenFolderClick;
            _toolbarPanel.Controls.Add(_openFolderButton);

            // Status label
            _statusLabel = new Label
            {
                Text = "UI Gallery - View and capture Clouseau dialogs",
                Location = new Point(350, 15),
                AutoSize = true,
                ForeColor = DarkTextDim,
                Font = new Font("Segoe UI", 9f)
            };
            _toolbarPanel.Controls.Add(_statusLabel);

            Controls.Add(_toolbarPanel);
        }

        /// <summary>
        /// Initializes the gallery flow layout panel.
        /// </summary>
        private void InitializeGalleryPanel()
        {
            _galleryPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                BackColor = DarkBackground,
                AutoScroll = true,
                Padding = new Padding(10),
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = true
            };

            Controls.Add(_galleryPanel);
        }

        /// <summary>
        /// Populates the gallery with items for each UI component.
        /// </summary>
        private void PopulateGalleryItems()
        {
            _galleryPanel.Controls.Clear();
            _galleryItems.Clear();

            // Dashboard Form
            var dashboardItem = CreateGalleryItem(
                "DashboardForm",
                "Main dashboard with Overview, Events, Metrics, Plugins, Dumps, and Spy tabs.",
                () => FindOpenForm<DashboardForm>(),
                () => OpenDashboard());
            _galleryItems.Add(dashboardItem);
            _galleryPanel.Controls.Add(dashboardItem.Panel);

            // Settings Dialog
            var settingsItem = CreateGalleryItem(
                "SettingsDialog",
                "Configuration dialog for all Clouseau settings.",
                () => FindOpenForm<SettingsDialog>(),
                () => OpenSettings());
            _galleryItems.Add(settingsItem);
            _galleryPanel.Controls.Add(settingsItem.Panel);

            // Log Viewer Window (pop-out)
            var logViewerItem = CreateGalleryItem(
                "LogViewerWindow",
                "Full-size pop-out log viewer with filtering and search.",
                () => FindOpenForm<LogViewerWindow>(),
                () => OpenLogViewer());
            _galleryItems.Add(logViewerItem);
            _galleryPanel.Controls.Add(logViewerItem.Panel);

            // Method Invoker Form
            var methodInvokerItem = CreateGalleryItem(
                "MethodInvokerForm",
                "Reflection-based method execution tool.",
                () => FindOpenForm<MethodInvokerForm>(),
                null); // Opened from Dashboard
            methodInvokerItem.OpenButton.Enabled = false;
            methodInvokerItem.OpenButton.Text = "Via Dashboard";
            _galleryItems.Add(methodInvokerItem);
            _galleryPanel.Controls.Add(methodInvokerItem.Panel);

            // Event Inspector Form
            var eventInspectorItem = CreateGalleryItem(
                "EventInspectorForm",
                "Event handler inspection and management.",
                () => FindOpenForm<EventInspectorForm>(),
                null); // Opened from Dashboard
            eventInspectorItem.OpenButton.Enabled = false;
            eventInspectorItem.OpenButton.Text = "Via Dashboard";
            _galleryItems.Add(eventInspectorItem);
            _galleryPanel.Controls.Add(eventInspectorItem.Panel);

            // Menu Inspector Form
            var menuInspectorItem = CreateGalleryItem(
                "MenuInspectorForm",
                "Menu hierarchy inspection tool.",
                () => FindOpenForm<MenuInspectorForm>(),
                null); // Opened from Dashboard
            menuInspectorItem.OpenButton.Enabled = false;
            menuInspectorItem.OpenButton.Text = "Via Dashboard";
            _galleryItems.Add(menuInspectorItem);
            _galleryPanel.Controls.Add(menuInspectorItem.Panel);

            // UI Gallery (self-reference)
            var galleryItem = CreateGalleryItem(
                "UIGalleryForm",
                "This form - displays all UI components.",
                () => this,
                null); // Can't open another instance while viewing
            galleryItem.OpenButton.Enabled = false;
            galleryItem.OpenButton.Text = "(Current)";
            _galleryItems.Add(galleryItem);
            _galleryPanel.Controls.Add(galleryItem.Panel);

            // Update all items
            UpdateAllItems();
        }

        /// <summary>
        /// Creates a gallery item panel for a UI component.
        /// </summary>
        private GalleryItem CreateGalleryItem(string name, string description, Func<Form> findForm, Action openAction)
        {
            var item = new GalleryItem
            {
                Name = name,
                Description = description,
                FindForm = findForm,
                OpenAction = openAction
            };

            // Main panel
            item.Panel = new Panel
            {
                Size = new Size(ItemPanelWidth, ItemPanelHeight),
                Margin = new Padding(8),
                BackColor = DarkPanel,
                Padding = new Padding(5)
            };

            // Title label
            item.TitleLabel = new Label
            {
                Text = name,
                Location = new Point(5, 5),
                Size = new Size(ItemPanelWidth - 10, 20),
                ForeColor = DarkText,
                Font = new Font("Segoe UI", 10f, FontStyle.Bold)
            };
            item.Panel.Controls.Add(item.TitleLabel);

            // Thumbnail panel (placeholder for screenshot)
            item.ThumbnailPanel = new Panel
            {
                Location = new Point(10, 28),
                Size = new Size(ThumbnailWidth, ThumbnailHeight),
                BackColor = Color.FromArgb(35, 35, 38),
                BorderStyle = BorderStyle.FixedSingle
            };

            // Placeholder label
            item.PlaceholderLabel = new Label
            {
                Text = "No preview\n(Form not open)",
                Dock = DockStyle.Fill,
                ForeColor = DarkTextDim,
                TextAlign = ContentAlignment.MiddleCenter,
                Font = new Font("Segoe UI", 9f)
            };
            item.ThumbnailPanel.Controls.Add(item.PlaceholderLabel);

            // Thumbnail PictureBox (initially hidden)
            item.ThumbnailPictureBox = new PictureBox
            {
                Dock = DockStyle.Fill,
                SizeMode = PictureBoxSizeMode.Zoom,
                Visible = false,
                BackColor = Color.FromArgb(35, 35, 38)
            };
            item.ThumbnailPanel.Controls.Add(item.ThumbnailPictureBox);

            item.Panel.Controls.Add(item.ThumbnailPanel);

            // Status label
            item.StatusLabel = new Label
            {
                Text = "Status: Closed",
                Location = new Point(5, 200),
                Size = new Size(ItemPanelWidth - 10, 18),
                ForeColor = StatusClosed,
                Font = new Font("Segoe UI", 8f)
            };
            item.Panel.Controls.Add(item.StatusLabel);

            // Info label
            item.InfoLabel = new Label
            {
                Text = description,
                Location = new Point(5, 218),
                Size = new Size(ItemPanelWidth - 10, 28),
                ForeColor = DarkTextDim,
                Font = new Font("Segoe UI", 7.5f),
                AutoEllipsis = true
            };
            item.Panel.Controls.Add(item.InfoLabel);

            // Button panel
            var buttonPanel = new Panel
            {
                Location = new Point(5, 248),
                Size = new Size(ItemPanelWidth - 10, 28),
                BackColor = Color.Transparent
            };

            // Open button
            item.OpenButton = CreateDarkButton("Open", DarkAccent);
            item.OpenButton.Size = new Size(70, 25);
            item.OpenButton.Location = new Point(0, 0);
            if (openAction != null)
            {
                item.OpenButton.Click += (s, e) => openAction();
            }
            else
            {
                item.OpenButton.Enabled = false;
            }
            buttonPanel.Controls.Add(item.OpenButton);

            // Capture button
            item.CaptureButton = CreateDarkButton("Capture", DarkPanel);
            item.CaptureButton.Size = new Size(70, 25);
            item.CaptureButton.Location = new Point(75, 0);
            item.CaptureButton.Click += (s, e) => CaptureForm(item);
            buttonPanel.Controls.Add(item.CaptureButton);

            // Focus button
            item.FocusButton = CreateDarkButton("Focus", DarkPanel);
            item.FocusButton.Size = new Size(70, 25);
            item.FocusButton.Location = new Point(150, 0);
            item.FocusButton.Enabled = false;
            item.FocusButton.Click += (s, e) => FocusForm(item);
            buttonPanel.Controls.Add(item.FocusButton);

            item.Panel.Controls.Add(buttonPanel);

            return item;
        }

        /// <summary>
        /// Creates a dark-themed button.
        /// </summary>
        private Button CreateDarkButton(string text, Color backColor)
        {
            var button = new Button
            {
                Text = text,
                BackColor = backColor,
                ForeColor = DarkText,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("Segoe UI", 8f)
            };
            button.FlatAppearance.BorderColor = DarkBorder;
            button.FlatAppearance.MouseOverBackColor = DarkHover;
            return button;
        }

        /// <summary>
        /// Updates all gallery items with current state.
        /// </summary>
        private void UpdateAllItems()
        {
            foreach (var item in _galleryItems)
            {
                UpdateGalleryItem(item);
            }
        }

        /// <summary>
        /// Updates a single gallery item's state.
        /// </summary>
        private void UpdateGalleryItem(GalleryItem item)
        {
            try
            {
                var form = item.FindForm?.Invoke();
                bool isOpen = form != null && !form.IsDisposed;

                if (isOpen)
                {
                    item.StatusLabel.Text = $"Status: Open";
                    item.StatusLabel.ForeColor = StatusOpen;
                    item.FocusButton.Enabled = true;
                    item.CaptureButton.Enabled = true;

                    // Update info with form details
                    var additionalInfo = GetFormInfo(form);
                    if (!string.IsNullOrEmpty(additionalInfo))
                    {
                        item.InfoLabel.Text = additionalInfo;
                    }

                    // Try to capture thumbnail
                    UpdateThumbnail(item, form);
                }
                else
                {
                    item.StatusLabel.Text = "Status: Closed";
                    item.StatusLabel.ForeColor = StatusClosed;
                    item.FocusButton.Enabled = false;
                    item.CaptureButton.Enabled = false;
                    item.InfoLabel.Text = item.Description;

                    // Show placeholder
                    item.PlaceholderLabel.Visible = true;
                    item.ThumbnailPictureBox.Visible = false;
                }
            }
            catch (Exception ex)
            {
                Logger.Trace($"Error updating gallery item {item.Name}: {ex.Message}");
            }
        }

        /// <summary>
        /// Gets additional info about an open form.
        /// </summary>
        private string GetFormInfo(Form form)
        {
            try
            {
                if (form is DashboardForm dashboard)
                {
                    var tabControl = FindControl<TabControl>(dashboard);
                    if (tabControl != null)
                    {
                        return $"Current tab: {tabControl.SelectedTab?.Text ?? "Unknown"}";
                    }
                }
                else if (form is SettingsDialog settings)
                {
                    var tabControl = FindControl<TabControl>(settings);
                    if (tabControl != null)
                    {
                        return $"Tab: {tabControl.SelectedTab?.Text ?? "Unknown"}";
                    }
                }
                else if (form is LogViewerWindow logViewer)
                {
                    var listBox = FindControl<ListBox>(logViewer);
                    if (listBox != null)
                    {
                        return $"Entries: {listBox.Items.Count}";
                    }
                }

                return $"Size: {form.Width}x{form.Height}";
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Finds a control of a specific type within a form.
        /// </summary>
        private T FindControl<T>(Control parent) where T : Control
        {
            foreach (Control control in parent.Controls)
            {
                if (control is T typedControl)
                    return typedControl;

                var found = FindControl<T>(control);
                if (found != null)
                    return found;
            }
            return null;
        }

        /// <summary>
        /// Updates the thumbnail for a gallery item.
        /// </summary>
        private void UpdateThumbnail(GalleryItem item, Form form)
        {
            try
            {
                if (form == null || form.IsDisposed || form.WindowState == FormWindowState.Minimized)
                    return;

                // Capture the form to a bitmap
                using (var bitmap = new Bitmap(form.Width, form.Height))
                {
                    form.DrawToBitmap(bitmap, new Rectangle(0, 0, form.Width, form.Height));

                    // Create thumbnail
                    var thumbnail = new Bitmap(ThumbnailWidth, ThumbnailHeight);
                    using (var graphics = Graphics.FromImage(thumbnail))
                    {
                        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        graphics.DrawImage(bitmap, 0, 0, ThumbnailWidth, ThumbnailHeight);
                    }

                    // Update picture box
                    var oldImage = item.ThumbnailPictureBox.Image;
                    item.ThumbnailPictureBox.Image = thumbnail;
                    item.ThumbnailPictureBox.Visible = true;
                    item.PlaceholderLabel.Visible = false;

                    // Dispose old image
                    oldImage?.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger.Trace($"Error updating thumbnail for {item.Name}: {ex.Message}");
                item.PlaceholderLabel.Text = "Preview error";
                item.PlaceholderLabel.Visible = true;
                item.ThumbnailPictureBox.Visible = false;
            }
        }

        /// <summary>
        /// Captures a screenshot of a form and saves it.
        /// </summary>
        private void CaptureForm(GalleryItem item)
        {
            try
            {
                // Don't capture the UI Gallery itself
                if (item.Name == "UIGalleryForm")
                {
                    MessageBox.Show("Cannot capture the UI Gallery itself.", "Cannot Capture",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                var form = item.FindForm?.Invoke();
                if (form == null || form.IsDisposed)
                {
                    MessageBox.Show($"{item.Name} is not currently open.", "Cannot Capture",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // Ensure screenshots folder exists
                var screenshotsPath = Path.Combine(_dataPath, "screenshots");
                if (!Directory.Exists(screenshotsPath))
                {
                    Directory.CreateDirectory(screenshotsPath);
                }

                // Generate filename
                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                var filename = $"{item.Name}_{timestamp}.png";
                var filePath = Path.Combine(screenshotsPath, filename);

                // Capture full-size screenshot
                if (form.WindowState == FormWindowState.Minimized)
                {
                    form.WindowState = FormWindowState.Normal;
                    form.BringToFront();
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(100);
                }

                using (var bitmap = new Bitmap(form.Width, form.Height))
                {
                    form.DrawToBitmap(bitmap, new Rectangle(0, 0, form.Width, form.Height));
                    bitmap.Save(filePath, ImageFormat.Png);
                }

                _statusLabel.Text = $"Captured: {filename}";
                Logger.Info($"Screenshot saved: {filePath}");

                // Update thumbnail
                UpdateThumbnail(item, form);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, $"Error capturing {item.Name}");
                MessageBox.Show($"Error capturing screenshot:\n{ex.Message}", "Capture Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Focuses an open form.
        /// </summary>
        private void FocusForm(GalleryItem item)
        {
            try
            {
                var form = item.FindForm?.Invoke();
                if (form != null && !form.IsDisposed)
                {
                    if (form.WindowState == FormWindowState.Minimized)
                    {
                        form.WindowState = FormWindowState.Normal;
                    }
                    form.BringToFront();
                    form.Focus();
                }
            }
            catch (Exception ex)
            {
                Logger.Trace($"Error focusing form {item.Name}: {ex.Message}");
            }
        }

        /// <summary>
        /// Finds an open form of a specific type.
        /// </summary>
        private Form FindOpenForm<T>() where T : Form
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form is T && !form.IsDisposed)
                {
                    return form;
                }
            }
            return null;
        }

        /// <summary>
        /// Opens the Dashboard form.
        /// </summary>
        private void OpenDashboard()
        {
            try
            {
                var existingDashboard = FindOpenForm<DashboardForm>();
                if (existingDashboard != null)
                {
                    existingDashboard.BringToFront();
                    existingDashboard.Focus();
                    return;
                }

                var dashboard = new DashboardForm(
                    _mbApi,
                    _dataPath,
                    _pluginsPath,
                    _settings,
                    _stateManager,
                    _metricsCollector,
                    _eventLogger);
                dashboard.Show();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error opening dashboard");
                MessageBox.Show($"Error opening Dashboard:\n{ex.Message}", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Opens the Settings dialog.
        /// </summary>
        private void OpenSettings()
        {
            try
            {
                var existingSettings = FindOpenForm<SettingsDialog>();
                if (existingSettings != null)
                {
                    existingSettings.BringToFront();
                    existingSettings.Focus();
                    return;
                }

                var settings = new SettingsDialog(_settings, _dataPath);
                settings.Show();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error opening settings");
                MessageBox.Show($"Error opening Settings:\n{ex.Message}", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Opens the Log Viewer window.
        /// </summary>
        private void OpenLogViewer()
        {
            try
            {
                var existingViewer = FindOpenForm<LogViewerWindow>();
                if (existingViewer != null)
                {
                    existingViewer.BringToFront();
                    existingViewer.Focus();
                    return;
                }

                // Create log viewer with event logger access
                var logViewer = new LogViewerWindow(
                    () => _eventLogger,
                    () => _stateManager,
                    null);
                logViewer.Show();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error opening log viewer");
                MessageBox.Show($"Error opening Log Viewer:\n{ex.Message}", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Starts the refresh timer for updating thumbnails.
        /// </summary>
        private void StartRefreshTimer()
        {
            _refreshTimer = new Timer { Interval = 2000 };
            _refreshTimer.Tick += (s, e) => UpdateAllItems();
            _refreshTimer.Start();
        }

        #region Event Handlers

        /// <summary>
        /// Handles Capture All button click.
        /// </summary>
        private void OnCaptureAllClick(object sender, EventArgs e)
        {
            try
            {
                var screenshotsPath = Path.Combine(_dataPath, "screenshots");
                if (!Directory.Exists(screenshotsPath))
                {
                    Directory.CreateDirectory(screenshotsPath);
                }

                int capturedCount = 0;
                var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");

                foreach (var item in _galleryItems)
                {
                    // Skip capturing the UI Gallery itself
                    if (item.Name == "UIGalleryForm") continue;

                    var form = item.FindForm?.Invoke();
                    if (form != null && !form.IsDisposed && form.WindowState != FormWindowState.Minimized)
                    {
                        try
                        {
                            var filename = $"{item.Name}_{timestamp}.png";
                            var filePath = Path.Combine(screenshotsPath, filename);

                            using (var bitmap = new Bitmap(form.Width, form.Height))
                            {
                                form.DrawToBitmap(bitmap, new Rectangle(0, 0, form.Width, form.Height));
                                bitmap.Save(filePath, ImageFormat.Png);
                            }

                            capturedCount++;
                            Logger.Info($"Screenshot saved: {filePath}");
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn($"Failed to capture {item.Name}: {ex.Message}");
                        }
                    }
                }

                _statusLabel.Text = $"Captured {capturedCount} screenshots to screenshots folder";

                if (capturedCount == 0)
                {
                    MessageBox.Show("No open dialogs to capture.\nOpen some dialogs first using the Open buttons.",
                        "No Dialogs Open", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"Captured {capturedCount} screenshots to:\n{screenshotsPath}",
                        "Capture Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error in Capture All");
                MessageBox.Show($"Error capturing screenshots:\n{ex.Message}", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Handles Refresh button click.
        /// </summary>
        private void OnRefreshClick(object sender, EventArgs e)
        {
            UpdateAllItems();
            _statusLabel.Text = "Gallery refreshed";
        }

        /// <summary>
        /// Handles Open Folder button click.
        /// </summary>
        private void OnOpenFolderClick(object sender, EventArgs e)
        {
            try
            {
                var screenshotsPath = Path.Combine(_dataPath, "screenshots");
                if (!Directory.Exists(screenshotsPath))
                {
                    Directory.CreateDirectory(screenshotsPath);
                }

                System.Diagnostics.Process.Start("explorer.exe", screenshotsPath);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error opening screenshots folder");
                MessageBox.Show($"Error opening folder:\n{ex.Message}", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        /// <summary>
        /// Cleans up resources when the form is closing.
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _refreshTimer?.Stop();
            _refreshTimer?.Dispose();

            // Dispose thumbnails
            foreach (var item in _galleryItems)
            {
                item.ThumbnailPictureBox?.Image?.Dispose();
            }

            base.OnFormClosing(e);
        }

        /// <summary>
        /// Represents a gallery item for a UI component.
        /// </summary>
        private class GalleryItem
        {
            public string Name { get; set; }
            public string Description { get; set; }
            public Func<Form> FindForm { get; set; }
            public Action OpenAction { get; set; }

            // UI Controls
            public Panel Panel { get; set; }
            public Label TitleLabel { get; set; }
            public Panel ThumbnailPanel { get; set; }
            public Label PlaceholderLabel { get; set; }
            public PictureBox ThumbnailPictureBox { get; set; }
            public Label StatusLabel { get; set; }
            public Label InfoLabel { get; set; }
            public Button OpenButton { get; set; }
            public Button CaptureButton { get; set; }
            public Button FocusButton { get; set; }
        }
    }
}
