using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Animation;
using System;
using Windows.UI;


namespace Sonex.Client.Animations
{


    public static class ColorPulse
    {
        private static readonly DependencyProperty SbProperty =
            DependencyProperty.RegisterAttached("Sb", typeof(Storyboard), typeof(ColorPulse), new PropertyMetadata(null));

        private static readonly DependencyProperty BrushProperty =
            DependencyProperty.RegisterAttached("Brush", typeof(SolidColorBrush), typeof(ColorPulse), new PropertyMetadata(null));

        private static readonly DependencyProperty OldBgProperty =
            DependencyProperty.RegisterAttached("OldBg", typeof(Brush), typeof(ColorPulse), new PropertyMetadata(null));

        private static readonly DependencyProperty HandlerProperty =
            DependencyProperty.RegisterAttached("Handler", typeof(RoutedEventHandler), typeof(ColorPulse), new PropertyMetadata(null));

        public static void Start(Control button, Color? to = null)
        {
            Stop(button);

            var oldBg = button.Background;
            button.SetValue(OldBgProperty, oldBg);

            var brush = new SolidColorBrush(Colors.Transparent);
            button.Background = brush;
            button.SetValue(BrushProperty, brush);

            var anim = new ColorAnimation
            {
                From = Colors.Transparent,
                To = to ?? Colors.Orange,
                Duration = TimeSpan.FromMilliseconds(400),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever,
                EasingFunction = new SineEase { EasingMode = EasingMode.EaseInOut }
            };

            var sb = new Storyboard();
            Storyboard.SetTarget(anim, brush);
            Storyboard.SetTargetProperty(anim, "Color");
            sb.Children.Add(anim);

            button.SetValue(SbProperty, sb);
            sb.AutoReverse = true;
            sb.RepeatBehavior = RepeatBehavior.Forever;
            sb.Begin();
        }

        public static void Stop(Control button)
        {
            if (button.GetValue(SbProperty) is Storyboard sb)
            {
                sb.Stop();
                button.ClearValue(SbProperty);
            }

            if (button.GetValue(OldBgProperty) is Brush oldBg)
            {
                button.Background = oldBg; // przywróć
                button.ClearValue(OldBgProperty);
            }
            else
            {
                button.Background = null;
            }

            button.ClearValue(BrushProperty);
        }
    }
}
