using DoomDeathmatch.Component.UI;
using DoomDeathmatch.Scene.Main;
using DoomDeathmatch.Script.Score;
using Engine.Graphics.Pipeline;
using Engine.Input;
using Engine.Util;
using OpenTK.Mathematics;

namespace DoomDeathmatch.Scene.GameOver;

public static class GameOverScene
{
  public static Engine.Scene.Scene Create(int parScore)
  {
    var scene = new Engine.Scene.Scene();

    var (cameraObject, camera) = UiUtil.CreateOrthographicCamera(scene);

    var (uiContainerObject, uiContainer) =
      UiUtil.CreateBackgroundUi(scene, new UiContainerComponent { Camera = camera });

    var (logoObject, logoUi) = UiUtil.CreateLogoUi(scene, uiContainer);
    logoUi.Offset = new Vector2(0, 3f);
    scene.AddChild(uiContainerObject, logoObject);

    var (resultUiObject, resultUi, _) =
      UiUtil.CreateTextUi(scene, uiContainer, UiUtil.GetDoomFont(), $"Ваш результат: {parScore}");

    var (nameUiObject, nameUi, (_, nameTextRenderer)) =
      UiUtil.CreateTextUi(scene, uiContainer, UiUtil.GetDoomFont(), "Имя: ");

    var nameInputComponent = new TextInputComponent { IsActive = true };
    nameInputComponent.OnInput += parName =>
    {
      nameTextRenderer.Text = $"Имя: {parName}";
    };
    nameUiObject.AddComponent(nameInputComponent);

    var (nextUiObject, nextUi, _) =
      UiUtil.CreateTextUi(scene, uiContainer, UiUtil.GetDoomFont(), "Далее");
    nextUi.OnClick += _ =>
    {
      if (string.IsNullOrEmpty(nameInputComponent.Input))
        return;

      SubmitScore(nameInputComponent.Input, parScore);
      EngineUtil.SceneManager.TransitionTo(MainScene.Create);
    };

    var (selectorObject, selector) = UiUtil.CreateSelectorUi(scene,
      new SelectorComponent { Children = { nextUi }, SelectKey = KeyboardButtonCode.Enter }, RenderLayer.HUD);

    var (stackObject, stack) = UiUtil.CreateStackUi(scene,
      new StackComponent { Offset = new Vector2(0, -1f), Container = uiContainer, Children = { resultUi, nextUi } });
    stackObject.Transform.Size.Xy = new Vector2(1f, 6f);

    scene.AddChild(stackObject, resultUiObject);
    scene.AddChild(stackObject, nameUiObject);
    scene.AddChild(stackObject, nextUiObject);


    return scene;
  }

  private static void SubmitScore(string parUsername, int parScore)
  {
    var table = ScoreTable.LoadOrCreate(Path.Combine(EngineUtil.DataFolder, "leaders.json"));
    table.Rows.Add(new ScoreRow { Name = parUsername, Score = parScore });
    ScoreTable.Save(table, Path.Combine(EngineUtil.DataFolder, "leaders.json"));
  }
}