using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using NexusShell.Models;

namespace NexusShell.Converters;

public sealed class NexusDeviceSectionVisibilityConverter : IValueConverter
{
    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not NexusDeviceSection selected || parameter is not string raw)
        {
            return Visibility.Collapsed;
        }

        return Enum.TryParse<NexusDeviceSection>(raw, ignoreCase: true, out var section) &&
               selected == section
            ? Visibility.Visible
            : Visibility.Collapsed;
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
        throw new NotSupportedException();
}

public sealed class PercentToWidthConverter : IValueConverter
{
    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not int percent || parameter is not string maxWidthRaw ||
            !double.TryParse(maxWidthRaw, NumberStyles.Any, culture, out var maxWidth))
        {
            return 0d;
        }

        return Math.Clamp(percent, 0, 100) / 100d * maxWidth;
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
        throw new NotSupportedException();
}

public sealed class HealthStatusBrushConverter : IValueConverter
{
    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        var status = value?.ToString() ?? "Good";
        var color = status switch
        {
            "Critical" => Color.FromRgb(255, 77, 109),
            "Warning" => Color.FromRgb(255, 176, 32),
            _ => Color.FromRgb(0, 217, 255),
        };

        return new SolidColorBrush(color);
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
        throw new NotSupportedException();
}
