using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

namespace Sonex.Client.Controls;

public sealed partial class BoolProperty : UserControl
{
    public BoolProperty()
    {
        InitializeComponent();
        UpdateReadOnlyState();
    }

    public string Header
    {
        get => (string)GetValue(HeaderProperty);
        set => SetValue(HeaderProperty, value);
    }

    public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register(
            nameof(Header),
            typeof(string),
            typeof(BoolProperty),
            new PropertyMetadata(string.Empty));

    public bool? Value
    {
        get => (bool?)GetValue(ValueProperty);
        set => SetValue(ValueProperty, value);
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register(
            nameof(Value),
            typeof(bool?),
            typeof(BoolProperty),
            new PropertyMetadata(false));

    public string Text
    {
        get => (string)GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(
            nameof(Text),
            typeof(string),
            typeof(BoolProperty),
            new PropertyMetadata(string.Empty));

    public bool IsReadOnly
    {
        get => (bool)GetValue(IsReadOnlyProperty);
        set => SetValue(IsReadOnlyProperty, value);
    }

    public static readonly DependencyProperty IsReadOnlyProperty =
        DependencyProperty.Register(
            nameof(IsReadOnly),
            typeof(bool),
            typeof(BoolProperty),
            new PropertyMetadata(false, OnIsReadOnlyChanged));

    public GridLength HeaderWidth
    {
        get => (GridLength)GetValue(HeaderWidthProperty);
        set => SetValue(HeaderWidthProperty, value);
    }

    public static readonly DependencyProperty HeaderWidthProperty =
        DependencyProperty.Register(
            nameof(HeaderWidth),
            typeof(GridLength),
            typeof(BoolProperty),
            new PropertyMetadata(new GridLength(150)));

    private static void OnIsReadOnlyChanged(
        DependencyObject dependencyObject,
        DependencyPropertyChangedEventArgs args)
    {
        if (dependencyObject is BoolProperty property)
        {
            property.UpdateReadOnlyState();
        }
    }

    private void UpdateReadOnlyState()
    {
        ValueCheckBox.IsEnabled = !IsReadOnly;
    }
}
