using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using NexusShell.Services;
using NexusShell.Services.Diagnostics;

namespace NexusShell.Controls;

public partial class NexusDesktopConnectionField : UserControl
{
    private readonly Random _random = new();
    private readonly DispatcherTimer _rebuildTimer;
    private readonly NexusTimerRegistration _timerRegistration;

    public NexusDesktopConnectionField()
    {
        InitializeComponent();
        _rebuildTimer = new DispatcherTimer(DispatcherPriority.Background)
        {
            Interval = TimeSpan.FromMilliseconds(180),
        };
        _rebuildTimer.Tick += (_, _) =>
        {
            _rebuildTimer.Stop();
            Rebuild();
        };
        _timerRegistration = NexusTimerRegistry.Register(
            "desktop-connection-rebuild",
            nameof(NexusDesktopConnectionField),
            _rebuildTimer.Interval,
            uiThread: true,
            "Debounced connection background rebuild on resize");
        Loaded += OnLoaded;
        Unloaded += (_, _) =>
        {
            _rebuildTimer.Stop();
            _timerRegistration.Dispose();
        };
        SizeChanged += OnSizeChanged;
    }

    private void OnLoaded(object sender, RoutedEventArgs e) => QueueRebuild();

    private void OnSizeChanged(object sender, SizeChangedEventArgs e) => QueueRebuild();

    private void QueueRebuild()
    {
        _rebuildTimer.Stop();
        _rebuildTimer.Start();
    }

    private void Rebuild()
    {
        if (ActualWidth <= 0 || ActualHeight <= 0)
        {
            return;
        }

        LineCanvas.Children.Clear();
        var points = new List<Point>();
        var count = NexusMotionPreferences.ShouldReduceMotion()
            ? _random.Next(6, 10)
            : _random.Next(14, 22);

        for (var i = 0; i < count; i++)
        {
            points.Add(new Point(_random.NextDouble() * ActualWidth, _random.NextDouble() * ActualHeight));
        }

        for (var i = 0; i < points.Count; i++)
        {
            var j = (i + _random.Next(1, 4)) % points.Count;
            var brush = _random.NextDouble() > 0.5
                ? new SolidColorBrush(Color.FromArgb(0x22, 0x8A, 0x4F, 0xFF))
                : new SolidColorBrush(Color.FromArgb(0x22, 0x00, 0xD9, 0xFF));

            LineCanvas.Children.Add(new Line
            {
                X1 = points[i].X,
                Y1 = points[i].Y,
                X2 = points[j].X,
                Y2 = points[j].Y,
                Stroke = brush,
                StrokeThickness = 0.8,
            });
        }
    }
}
