using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using NexusShell.Helpers;

namespace NexusShell.Controls;

public partial class NexusTitleBar : UserControl
{
    public static readonly DependencyProperty AppTitleProperty =
        DependencyProperty.Register(nameof(AppTitle), typeof(string), typeof(NexusTitleBar),
            new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty AppSubtitleProperty =
        DependencyProperty.Register(nameof(AppSubtitle), typeof(string), typeof(NexusTitleBar),
            new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty IconDataProperty =
        DependencyProperty.Register(nameof(IconData), typeof(string), typeof(NexusTitleBar),
            new PropertyMetadata(string.Empty, OnIconDataChanged));

    public static readonly DependencyProperty ShowChromeButtonsProperty =
        DependencyProperty.Register(nameof(ShowChromeButtons), typeof(bool), typeof(NexusTitleBar),
            new PropertyMetadata(true, OnShowChromeButtonsChanged));

    public NexusTitleBar()
    {
        InitializeComponent();
        Loaded += (_, _) => UpdateChromeVisibility();
    }

    public string AppTitle
    {
        get => (string)GetValue(AppTitleProperty);
        set => SetValue(AppTitleProperty, value);
    }

    public string AppSubtitle
    {
        get => (string)GetValue(AppSubtitleProperty);
        set => SetValue(AppSubtitleProperty, value);
    }

    public string IconData
    {
        get => (string)GetValue(IconDataProperty);
        set => SetValue(IconDataProperty, value);
    }

    public bool ShowChromeButtons
    {
        get => (bool)GetValue(ShowChromeButtonsProperty);
        set => SetValue(ShowChromeButtonsProperty, value);
    }

    private static void OnIconDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is NexusTitleBar bar && e.NewValue is string data && !string.IsNullOrWhiteSpace(data))
        {
            try
            {
                bar.IconPath.Data = Geometry.Parse(data);
            }
            catch (FormatException)
            {
                // Keep default icon geometry when path data is invalid.
            }
        }
    }

    private static void OnShowChromeButtonsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is NexusTitleBar bar)
        {
            bar.UpdateChromeVisibility();
        }
    }

    private void UpdateChromeVisibility()
    {
        ChromeButtons.Visibility = ShowChromeButtons ? Visibility.Visible : Visibility.Collapsed;
    }

    private void TitleBar_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (Window.GetWindow(this) is { } window)
        {
            NexusAppWindowHelper.HandleTitleBarMouseDown(window, e);
        }
    }
}
