using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace NexusShell.Controls;

public partial class NexusModal : UserControl
{
    public static readonly DependencyProperty IsOpenProperty =
        DependencyProperty.Register(nameof(IsOpen), typeof(bool), typeof(NexusModal),
            new PropertyMetadata(false, OnIsOpenChanged));

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register(nameof(Title), typeof(string), typeof(NexusModal),
            new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty BodyContentProperty =
        DependencyProperty.Register(nameof(BodyContent), typeof(object), typeof(NexusModal),
            new PropertyMetadata(null));

    public static readonly DependencyProperty FooterContentProperty =
        DependencyProperty.Register(nameof(FooterContent), typeof(object), typeof(NexusModal),
            new PropertyMetadata(null));

    public static readonly DependencyProperty CloseOnOverlayClickProperty =
        DependencyProperty.Register(nameof(CloseOnOverlayClick), typeof(bool), typeof(NexusModal),
            new PropertyMetadata(true));

    public NexusModal()
    {
        InitializeComponent();
    }

    public bool IsOpen
    {
        get => (bool)GetValue(IsOpenProperty);
        set => SetValue(IsOpenProperty, value);
    }

    public string Title
    {
        get => (string)GetValue(TitleProperty);
        set => SetValue(TitleProperty, value);
    }

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

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

    public bool CloseOnOverlayClick
    {
        get => (bool)GetValue(CloseOnOverlayClickProperty);
        set => SetValue(CloseOnOverlayClickProperty, value);
    }

    private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is NexusModal modal)
        {
            modal.Visibility = e.NewValue is true ? Visibility.Visible : Visibility.Collapsed;
        }
    }

    private void Overlay_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (CloseOnOverlayClick)
        {
            IsOpen = false;
        }
    }
}
