using GraphicsManager.Enums;
using GraphicsManager.Interfaces;
using GraphicsManager.Objects;
using GraphicsManager.Objects.Core;
using OpenTK.Mathematics;

namespace Luski.GUI.MainScreen.UI.SettingsPanel;

public class CategoryButton : UserControl
{
    public static Texture? seltec = null;
    private SettingsMenu SM;
    private Label l;
    public required Action OnPageLoad;
    
    public CategoryButton(string Text, SettingsMenu SM)
    :base(seltec)
    {
        this.SM = SM;
        base.Size = new(297.ScaleInt(), 40.ScaleInt());
        TextureDisplay = TextureDisplay.HorizontalCenter;
        Shader = Rectangle.DefaultAlphaShader[Globals.ms.Context];
        l = new Label(Globals.DefaultFont)
        {
            Text = Text,
            Color = Color4.Gray,
            IgnoreHover = true
        };
        l.Location = new(5.ScaleInt(),
            ((base.Size.Y - l.Size.Y) / 2)
            , 0);
        Controls.Add(l);
        BackgroundColor = new(0, 0, 0, 0);
        Clicked += OnClicked;
        MouseEnter += o =>
        {
            if (!Selected)
            {
                BackgroundColor = new(141, 151, 165, 30);
            }
            return Task.CompletedTask;
        };
        MouseLeave += o =>
        {
            if (!Selected)
            {
                BackgroundColor = new(0,0,0,0);
            }
            return Task.CompletedTask;
        };
    }

    private async Task OnClicked(IRenderObject arg)
    {
        if (!Selected) await ToggleSelected();
    }

    public bool Selected { get; private set; }
    
    public async Task ToggleSelected()
    {
        try
        {
            Color4 bc = new(141,151,165,51), f= Color4.White;
            if (Selected)
            {
                bc = new (0,0,0,0);
                f = Color4.Gray;
            }
            
            BlockDraw = true;
            Selected = !Selected;

            if (SM.Selected is not null && SM.Selected != this)
            {
                await SM.Selected.ToggleSelected();
            }
            BackgroundColor = bc;
            l.Color = f;
            if (Selected)
            {
                SM.Selected = this;
                Globals.ms.Title = $"Settings | {l.Text} - Luski";
                SM.page.Controls.Clear();
                OnPageLoad.Invoke();
            }

            BlockDraw = false;
            TryDraw();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}