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

namespace Sonex.Client.Controls;

public delegate void TabPanelItemSelectedEventHandler(object sender, TabPanelItem item);

[ContentProperty(Name = nameof(Content))]
public sealed class TabPanelItem : SelectorBarItem
{
    private const string SelectorBarItemPaddingResourceKey = "SelectorBarItemPadding";

    public static readonly DependencyProperty ContentProperty =
        DependencyProperty.Register(
            nameof(Content),
            typeof(object),
            typeof(TabPanelItem),
            new PropertyMetadata(null, OnContentChanged));

    public TabPanelItem()
    {
        ApplyTabPadding(new Thickness(16, 8, 16, 6));
        Background = new SolidColorBrush(Colors.Transparent);
        HorizontalAlignment = HorizontalAlignment.Stretch;
        HorizontalContentAlignment = HorizontalAlignment.Stretch;
        VerticalContentAlignment = VerticalAlignment.Stretch;
    }

    public string Header
    {
        get => Text;
        set => Text = value ?? string.Empty;
    }

    public Thickness TabPadding
    {
        get => Padding;
        set => ApplyTabPadding(value);
    }

    public object? Content
    {
        get => GetValue(ContentProperty);
        set => SetValue(ContentProperty, value);
    }

    public event TabPanelItemSelectedEventHandler? OnSelect;

    internal event EventHandler? ContentChanged;

    internal void RaiseOnSelect()
    {
        OnSelect?.Invoke(this, this);
    }

    private static void OnContentChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs _)
    {
        if (dependencyObject is TabPanelItem item)
        {
            item.ContentChanged?.Invoke(item, EventArgs.Empty);
        }
    }

    private void ApplyTabPadding(Thickness padding)
    {
        Padding = padding;
        Resources[SelectorBarItemPaddingResourceKey] = padding;
    }

}