using GraphicsManager.Enums;
using GraphicsManager.Interfaces;
using GraphicsManager.Objects;
using GraphicsManager.Objects.Core;
using Luski.GUI.MainScreen.UI.LuskiControls;
using Luski.GUI.MainScreen.UI.LuskiControls.ServerForms;
using OpenTK.Mathematics;
using OpenTK.Windowing.GraphicsLibraryFramework;

namespace Luski.GUI.MainScreen.UI;

public class AddServerOverlayForm : UserControl
{
    private TextBox tb;
    private CreateAccountUI caUI = new();
    private DropDown<VersionDropButton> version;
    private LoginUI lUI = new()
    {
        Visible = false
    };

    private UserControl btn;

    private TextBox UsernameTB
    {
        get
        {
            if (lUI.Visible) return lUI.Username;
            return caUI.Username;
        }
    }
    
    private TextBox PasswordTB
    {
        get
        {
            if (lUI.Visible) return lUI.Password;
            return caUI.Password;
        }
    }
    
    public AddServerOverlayForm()
    :base(Globals.ms.TextureManager.GetTextureResource("RoundedRectangle.png"))
    {
        base.Size = new(350.ScaleInt(), 347.ScaleInt());
        base.BackgroundColor = new(32, 32, 32, 255);
        Shader = Rectangle.DefaultAlphaShader[Globals.ms.Context];
        TextureDisplay = TextureDisplay.Center;
        Label t;
        Controls.Add(t=new Label(Globals.DefaultFont) { Scale = 1.6f, Text = "Add Server", Color = Globals.DodgerBlue });
        t.Location = new((base.Size.X / 2) - (t.Size.X / 2), t.Location.Y);

        Label? ll = new Label(Globals.DefaultFont)
        {
            Text = net.API.DefaultVersion,
            Color = Color4.DarkGray,
            IgnoreHover = true
        };
        Vector2i s =new((int)(ll.Size.X * 1.6f),27.ScaleInt());
        ll = null;
        
        Rectangle line = new Rectangle()
        {
            Size = new Vector2i(1.ScaleInt()),
            BackgroundColor = Globals.DodgerBlue
        };

        int ten = 10.ScaleInt();
        
        tb = new("BadTextbox.png")
        {
            Location = new(ten,50.ScaleInt()),
            Size = (base.Size.X - ten - ten - ten - s.X, s.Y),
            WatermarkText = "Server Address",
            TextLocation = TextLocation.LineCenter,
            AllowMultiLine = false
        };
        tb.LetterPress += () =>
        {
            Texture good = Globals.ms.TextureManager.GetTextureResource("Textbox.png");
                    
            if (tb.Textures[0].handel != good.handel)
            {
                tb.Textures[0] = good;
                if (UsernameTB.Textures[0].handel == good.handel &&
                    PasswordTB.Textures[0].handel == good.handel &&
                    (lUI.Visible || caUI.Avatar.Textures.Count > 1) &&
                    btn!.Textures[0].handel != good.handel &&
                    tb.Textures[0].handel == good.handel)
                {
                    btn.Textures[0] = good;
                }
                Globals.ms.TryDraw();
            }
            return Task.CompletedTask;
        };
        tb.LetterRemoved += () =>
        {
            Texture bad = Globals.ms.TextureManager.GetTextureResource("BadTextbox.png");
                    
            if (tb.Text.Length == 0 && tb.Textures[0].handel != bad.handel)
            {
                tb.Textures[0] = bad;
                btn!.Textures[0] = bad;
                Globals.ms.TryDraw();
            }
                    
            return Task.CompletedTask;
        };
        tb.KeyPress += args =>
        {
            if (args.Key == Keys.Tab && !args.Shift)
            {
                UsernameTB.Focus();
            }

            return Task.CompletedTask;
        };
        
        Controls.Add(tb);
        
        version = new DropDown<VersionDropButton>(Textures[0], line)
        {
            DropDownParentOverride = this,
            Size = s,
            BackgroundColor = new(255,20,20,255),
            TextureDisplay = TextureDisplay.HorizontalCenter,
            Shader = Shader,
            Location = new(tb.Location.X + tb.Size.X + tb.Location.X, tb.Location.Y)
        };
        
        foreach (string v in Globals.Luski.SupportedVersions)
        {
            VersionDropButton option = new VersionDropButton(s, v)
            {
                LoadDisplay = () =>
                {
                    try
                    {
                        Label ll2 = new Label(Globals.DefaultFont)
                        {
                            Text = v,
                            Color = Color4.DarkGray,
                            IgnoreHover = true,

                        };
                        ll2.Location = new((version.Size.X / 2) - (ll2.Size.X / 2),
                            ((version.Size.Y - ll2.Size.Y) / 2));
                        version.Controls.Add(ll2);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            };
            version.AddOption(option);
            if (v == net.API.DefaultVersion)
            {
                version.SetSelected(option);
            }
        }
        
        version.OpenStatusChanged += VersionOnOpenStatusChanged;
        version.OptionSelected += VersionOnOptionSelected;
        
        
        version.DropDownContainer.Textures.Add(Globals.ms.TextureManager.GetTextureResource("RoundedRectangleBottom.png"));
        version.DropDownContainer.TextureDisplay = TextureDisplay.Center;
        version.DropDownContainer.Shader = Rectangle.DefaultAlphaShader[Globals.ms.Context];
        version.DropDownContainer.BackgroundColor = version.BackgroundColor;
        version.OpenStatusChanged += b =>
        {
            BlockDraw = true;
            if (b)
            {
                version.Textures[0] = Globals.ms.TextureManager.GetTextureResource("RoundedRectangleTop.png");
            }
            else
            {
                version.Textures[0] = Globals.ms.TextureManager.GetTextureResource("RoundedRectangle.png");
            }

            BlockDraw = false;
            return Task.CompletedTask;
        };
        
        
        btn = new(Globals.ms.TextureManager.GetTextureResource("BadTextbox.png"))
        {
            Location = new(tb.Location.X, tb.Location.Y + tb.Size.Y + tb.Location.X),
            Size = new(tb.Size.X, tb.Size.Y),
            TextureDisplay = TextureDisplay.Center
        };
        Label sub = new(Globals.DefaultFont)
        {
            Text = "Submit",
            IgnoreHover = true
        };
        sub.Location = new((btn.Size.X / 2) - (sub.Size.X / 2),
            ((btn.Size.Y - sub.Size.Y) / 2));
        sub.ForceDistanceUpdate(btn);
        btn.Controls.Add(sub);
        Controls.Add(btn);
    }
    
    private Task VersionOnOpenStatusChanged(bool arg)
    {
        return Task.CompletedTask;
    }
    
    private Task VersionOnOptionSelected(VersionDropButton arg)
    {
        return Task.CompletedTask;
    }
    
    public override void ParentResize()
    {
	    BlockDraw = true;
	    for (int i = 0; i < Controls.Length; i++)
	    {
		    if (!Controls[i].Loaded) continue;
		    bool top = (Controls[i].Anchor & ObjectAnchor.Top) == ObjectAnchor.Top;
		    bool left = (Controls[i].Anchor & ObjectAnchor.Left) == ObjectAnchor.Left;
		    bool right = (Controls[i].Anchor & ObjectAnchor.Right) == ObjectAnchor.Right;
		    bool bottom = (Controls[i].Anchor & ObjectAnchor.Bottom) == ObjectAnchor.Bottom;
		    if (!top && !bottom) { Controls[i].Anchor |= ObjectAnchor.Top; top = true; }
		    if (!left && !right) { Controls[i].Anchor |= ObjectAnchor.Left; left = true; }
		    
		    int lx, ly, sy, sx;
		    bool UpdateDistance = false;
		    if ((Controls[i].Anchor & ObjectAnchor.PreventWidthChange) == ObjectAnchor.PreventWidthChange)
		    {
			    UpdateDistance = true;
			    lx = Controls[i].Location.X + ((Size.X - Controls[i].Distance.X - Controls[i].Size.X - Controls[i].Location.X) / 2);
			    sx = Controls[i].Size.X;
		    }
		    else
		    {
			    lx = (left ? Controls[i].Location.X : Size.X - Controls[i].Distance.X - Controls[i].Size.X);
			    sx = (right ? Size.X - Controls[i].Distance.X - lx : Controls[i].Size.X);
		    }
		    if ((Controls[i].Anchor & ObjectAnchor.PreventHeightChange) == ObjectAnchor.PreventHeightChange)
		    {
			    UpdateDistance = true;
			    ly = Controls[i].Location.Y + ((Size.Y - Controls[i].Distance.Y - Controls[i].Size.Y - Controls[i].Location.Y) / 2);
			    sy = Controls[i].Size.Y;
		    }
		    else
		    {
			    ly = (top ? Controls[i].Location.Y : Size.Y - Controls[i].Distance.Y - Controls[i].Size.Y);
			    sy = (bottom ? Size.Y - Controls[i].Distance.Y - ly : Controls[i].Size.Y);
		    }
		    
		    bool mooved = false;
            Console.WriteLine(Controls[i].Location);
            Console.WriteLine(Controls[i].Size);
            Console.WriteLine("New X:{0} Y:{1} W:{2} H:{3}", lx, ly, sx, sy);
		    if (sx != Controls[i].Size.X || sy != Controls[i].Size.Y)
		    {
			    mooved = true;
			    Controls[i].SetSize(sx, sy);
		    }
		    if (lx != Controls[i].Location.X || ly != Controls[i].Location.Y)
		    {
			    mooved = true;
			    Controls[i].SetLocation(lx, ly);
		    }
		    if (UpdateDistance)
		    {
			    Controls[i].ForceDistanceUpdate(this);
		    }
            Console.WriteLine(mooved);
		    if (Controls[i] is IParent parent)
		    {
                Console.WriteLine(Controls[i]);
			    parent.ParentResize();
		    }
	    }
	    if (Parent is not null) Parent.TryDraw();
	    BlockDraw = false;
    }
}