using System;
using System.Collections.Generic;
using System.Linq;
using LittleSim.App;
using LittleSim.Content;
using LittleSim.UI;
using Microsoft.Xna.Framework.Input;
using MrGameEng.Core;
using MrGameEng.Host;
using MrGameEng.Input;
using MrGameEng.UI;
using Myra.Graphics2D.UI;

namespace LittleSim.Scenes;

/// <summary>
/// Окно настройки нового мира: имя, размер (пресеты из <see cref="WorldPresetDef"/> Core-мода),
/// сид (с кнопкой «случайно») и сглаживание рельефа. «Создать» запускает <see cref="WorldScene"/>.
/// </summary>
public sealed class NewWorldScene : Scene
{
    private const int MinSmoothing = 1;
    private const int MaxSmoothing = 8;

    private WorldPresetDef _preset = null!;
    private int _smoothing = 4;
    private TextBox _name = null!;
    private TextBox _seed = null!;
    private readonly List<Action> _refreshers = [];

    protected override void OnLoad()
    {
        var content = Context.Services.Get<GameContent>();
        var lang = content.Languages;
        var input = this.UseInput();
        var desktop = this.UseUI(); // ставит MyraEnvironment.Game до создания виджетов

        var presets = content.Defs.All<WorldPresetDef>().OrderBy(p => p.Order).ToList();
        _preset = presets[0];

        var column = Ui.Column(10);
        column.Widgets.Add(Ui.Title(lang.Get("newworld.title")));
        column.Widgets.Add(new Label { Height = 8 });

        _name = new TextBox { Text = lang.Get("newworld.defaultname"), Width = 280 };
        column.Widgets.Add(LabeledRow(lang.Get("newworld.name"), _name));

        // Размер — сегменты пресетов.
        var sizeRow = Ui.Row(6);
        sizeRow.Widgets.Add(new Label { Text = lang.Get("newworld.size"), TextColor = Ui.Muted });
        foreach (var preset in presets)
        {
            var value = preset;
            var button = new TextButton { Text = lang.Get(preset.Label) };
            button.Click += (_, _) =>
            {
                _preset = value;
                Refresh();
            };
            sizeRow.Widgets.Add(button);
            _refreshers.Add(() =>
                button.TextColor = ReferenceEquals(_preset, value) ? Ui.Accent : Ui.Muted
            );
        }

        column.Widgets.Add(sizeRow);

        // Сид + случайно.
        _seed = new TextBox { Text = Random.Shared.Next().ToString(), Width = 200 };
        var seedRow = Ui.Row(6);
        seedRow.Widgets.Add(new Label { Text = lang.Get("newworld.seed"), TextColor = Ui.Muted });
        seedRow.Widgets.Add(_seed);
        seedRow.Widgets.Add(
            Ui.Button(
                lang.Get("newworld.random"),
                () => _seed.Text = Random.Shared.Next().ToString(),
                width: 120
            )
        );
        column.Widgets.Add(seedRow);

        // Сглаживание −/+.
        var smoothRow = Ui.Row(6);
        var smoothLabel = new Label { TextColor = Ui.Muted };
        _refreshers.Add(() => smoothLabel.Text = $"{lang.Get("newworld.smoothing")}: {_smoothing}");
        var minus = new TextButton { Text = "−" };
        minus.Click += (_, _) =>
        {
            _smoothing = Math.Max(MinSmoothing, _smoothing - 1);
            Refresh();
        };
        var plus = new TextButton { Text = "+" };
        plus.Click += (_, _) =>
        {
            _smoothing = Math.Min(MaxSmoothing, _smoothing + 1);
            Refresh();
        };
        smoothRow.Widgets.Add(smoothLabel);
        smoothRow.Widgets.Add(minus);
        smoothRow.Widgets.Add(plus);
        column.Widgets.Add(smoothRow);

        column.Widgets.Add(new Label { Height = 8 });
        var buttons = Ui.Row(10);
        buttons.Widgets.Add(Ui.Button(lang.Get("newworld.create"), Create, width: 150));
        buttons.Widgets.Add(Ui.Button(lang.Get("newworld.back"), Back, width: 150));
        column.Widgets.Add(buttons);

        desktop.Root = Ui.Screen(column);
        Refresh();

        UpdateSystems.Add(
            new CallbackSystem(() =>
            {
                if (input.IsKeyPressed(Keys.Escape))
                {
                    Back();
                }
            })
        );
    }

    private static Widget LabeledRow(string label, Widget control)
    {
        var row = Ui.Row(6);
        row.Widgets.Add(new Label { Text = label, TextColor = Ui.Muted });
        row.Widgets.Add(control);
        return row;
    }

    private void Refresh()
    {
        foreach (var refresh in _refreshers)
        {
            refresh();
        }
    }

    private void Create()
    {
        if (Context.Scenes.IsTransitioning)
        {
            return;
        }

        var seed = int.TryParse(_seed.Text, out var parsed) ? parsed : Random.Shared.Next();
        var name = string.IsNullOrWhiteSpace(_name.Text) ? "World" : _name.Text.Trim();
        var config = new WorldConfig
        {
            Name = name,
            Width = _preset.Width,
            Height = _preset.Height,
            Population = _preset.Population,
            Seed = seed,
            SmoothPasses = _smoothing,
        };
        Context.Scenes.Switch(new WorldScene(config), Transitions.Fade(0.6f));
    }

    private void Back()
    {
        if (!Context.Scenes.IsTransitioning)
        {
            Context.Scenes.Switch(new MainMenuScene(), Transitions.Fade(0.4f));
        }
    }
}
