using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace CamBooth.App.Features.LiveView;

public partial class TimerControlRectangleAnimation : UserControl
{
// Ellipse diameter=320, StrokeThickness=12 → circumference = π*320/12 ≈ 83.78 dash-units
    private static readonly double RingFullDashUnits = Math.PI * 320.0 / 12.0;

    public static event Action? OnTimerEllapsed;

    private readonly DispatcherTimer _ticker = new() { Interval = TimeSpan.FromSeconds(1) };
    private readonly Random _random = new();

    private int _remainingTime;
    private double _totalDuration;

    private static readonly string[] Instructions =
    [
        "Lächeln! 😊", "Hasenohren machen! 🐰", "Zunge rausstrecken! 👅",
        "Grimasse ziehen! 😝", "Daumen hoch! 👍", "Peace-Zeichen! ✌️",
        "Lustig gucken! 🤪", "Crazy Face! 🤯", "Küsschen! 😘",
        "Winken! 👋", "Herz mit den Händen! ❤️", "Überrascht schauen! 😲",
        "Cool bleiben! 😎", "Lachen! 😄", "Zähne zeigen! 😁",
        "Schnute ziehen! 😗", "Arm hochstrecken! 🙌", "Gruppe umarmen! 🤗"
    ];


    public TimerControlRectangleAnimation()
    {
        InitializeComponent();
        _ticker.Tick += OnTick;
    }


    public void StartTimer(int durationInSeconds)
    {
        _totalDuration = durationInSeconds;
        _remainingTime = durationInSeconds;

        CountdownNumber.Text = _remainingTime.ToString();
        InstructionText.Text = Instructions[_random.Next(Instructions.Length)];

// Reset ring offset so ring appears full
        CountdownRing.StrokeDashOffset = 0;
        CountdownRing.StrokeDashArray = new DoubleCollection { RingFullDashUnits, RingFullDashUnits };

        FadeIn();
        StartRingAnimation();
        _ticker.Start();
    }


    private void OnTick(object? sender, EventArgs e)
    {
        _remainingTime--;

        if (_remainingTime > 0)
        {
            CountdownNumber.Text = _remainingTime.ToString();
            AnimateNumberPop();
        }
        else
        {
            _ticker.Stop();
            CountdownNumber.Text = "0";
            AnimateNumberPop();
            StopRingAnimation();
            OnTimerEllapsed?.Invoke();
        }
    }


    private void FadeIn()
    {
        TimerContainer.BeginAnimation(OpacityProperty,
            new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(300)));
    }


    private void StartRingAnimation()
    {
        // StrokeDashOffset IS a DependencyProperty — animate directly, no Storyboard needed.
        // Pattern: dash=C, gap=C. Offset 0 → full ring; offset C → empty ring.
        CountdownRing.BeginAnimation(Shape.StrokeDashOffsetProperty,
            new DoubleAnimation(0, RingFullDashUnits,
                new Duration(TimeSpan.FromSeconds(_totalDuration)))
            {
                FillBehavior = FillBehavior.HoldEnd
            });
    }


    private void StopRingAnimation() =>
        CountdownRing.BeginAnimation(Shape.StrokeDashOffsetProperty, null);


    private void AnimateNumberPop()
    {
        var easing = new BackEase { Amplitude = 0.4, EasingMode = EasingMode.EaseOut };
        CountdownNumberScale.ScaleX = 1.4;
        CountdownNumberScale.ScaleY = 1.4;
        CountdownNumberScale.BeginAnimation(ScaleTransform.ScaleXProperty,
            new DoubleAnimation(1.4, 1.0, TimeSpan.FromMilliseconds(450)) { EasingFunction = easing });
        CountdownNumberScale.BeginAnimation(ScaleTransform.ScaleYProperty,
            new DoubleAnimation(1.4, 1.0, TimeSpan.FromMilliseconds(450)) { EasingFunction = easing });
    }
}