using System;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;

namespace Sonex.Client.Controls;

public sealed class ToolBarToggleSplitButton : ToggleSplitButton
{
    public static readonly DependencyProperty IconSourceProperty = DependencyProperty.Register(
        nameof(IconSource),
        typeof(string),
        typeof(ToolBarToggleSplitButton),
        new PropertyMetadata(string.Empty, OnIconSourceChanged));

    private readonly Image _iconImage = new()
    {
        Width = 18,
        Height = 18,
        Stretch = Stretch.Uniform
    };

    private bool _iconManagedContent;

    public ToolBarToggleSplitButton()
    {
        MinWidth = 40;
        Height = 32;
        Padding = new Thickness(6);
        CornerRadius = new CornerRadius(4);
        BorderThickness = new Thickness(1);
        UseSystemFocusVisuals = false;
        FocusVisualPrimaryThickness = new Thickness(0);
        FocusVisualSecondaryThickness = new Thickness(0);
        HorizontalAlignment = HorizontalAlignment.Center;
        VerticalAlignment = VerticalAlignment.Center;
        Transitions = null;

        UpdateIconContent(IconSource);
    }

    public string IconSource
    {
        get => (string)GetValue(IconSourceProperty);
        set => SetValue(IconSourceProperty, value);
    }

    private static void OnIconSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is ToolBarToggleSplitButton control)
        {
            control.UpdateIconContent(e.NewValue as string);
        }
    }

    private void UpdateIconContent(string? source)
    {
        if (string.IsNullOrWhiteSpace(source))
        {
            if (_iconManagedContent)
            {
                Content = null;
                _iconManagedContent = false;
            }

            return;
        }

        var imageSource = CreateImageSource(source);
        if (imageSource == null)
        {
            return;
        }

        _iconImage.Source = imageSource;
        Content = _iconImage;
        _iconManagedContent = true;
    }

    private static ImageSource? CreateImageSource(string source)
    {
        if (!TryCreateUri(source, out var uri))
        {
            return null;
        }

        return source.Trim().EndsWith(".svg", StringComparison.OrdinalIgnoreCase)
            ? new SvgImageSource(uri)
            : new BitmapImage(uri);
    }

    private static bool TryCreateUri(string source, out Uri uri)
    {
        uri = null!;
        var normalized = source.Trim();

        if (Uri.TryCreate(normalized, UriKind.Absolute, out var absoluteUri) && absoluteUri is not null)
        {
            uri = absoluteUri;
            return true;
        }

        if (Uri.TryCreate($"ms-appx:///{normalized.TrimStart('/')}", UriKind.Absolute, out var appxUri) && appxUri is not null)
        {
            uri = appxUri;
            return true;
        }

        return false;
    }
}
