using System;
using System.Collections.Generic;
using System.Linq;
using eagle;
using Net.Eagle0.Eagle.Api;
using Net.Eagle0.Eagle.Common;
using Net.Eagle0.Eagle.Views;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Random = System.Random;

public class CreateGameItem : MonoBehaviour {
    private const int TotalPlayerCount = 7;

    public HeroDropdownController heroDropdownController;
    public TMP_Dropdown totalHumansDropdown;
    public Button createButton;
    public TextMeshProUGUI buttonText;

    public Action<string, int, int> CreateCallback;

    private List<AvailableLeader> availableLeaders;

    public string SelectedLeaderTextId {
        get {
            if (heroDropdownController.SelectedHeroId == 0) {
                var index = new Random().Next(availableLeaders.Count);
                return availableLeaders[index].NameTextId;
            } else {
                return availableLeaders[heroDropdownController.SelectedHeroId - 1].NameTextId;
            }
        }
    }

    public void CreateClicked() {
        CreateCallback(SelectedLeaderTextId, totalHumansDropdown.value + 1, TotalPlayerCount);
    }

    public void SetHumanPlayersDropdown() {
        var currentValue = totalHumansDropdown.value;
        totalHumansDropdown.ClearOptions();
        totalHumansDropdown.AddOptions(Enumerable.Range(1, TotalPlayerCount)
                                               .Select(i => i == 1 ? "1 player" : $"{i} players")
                                               .ToList());
        totalHumansDropdown.value = Math.Min(TotalPlayerCount - 1, currentValue);
    }

    public void SetCreationOptions(List<AvailableLeader> leaders) {
        this.availableLeaders = leaders;

        buttonText.text = "CREATE";

        List<HeroView> heroOptions =
                new List<HeroView> { new() { Id = 0, Profession = Profession.NoProfession } };
        for (int i = 0; i < leaders.Count; i++) {
            var leader = leaders[i];
            heroOptions.Add(new HeroView {
                NameTextId = leader.NameTextId,
                Profession = leader.Profession,
                Id = i + 1,
                ImagePath = leader.ImagePath
            });
        }

        // Pass pre-resolved names from AvailableLeader.Name so names display
        // immediately without needing to look them up via ClientTextProvider
        heroDropdownController.PreResolvedNames =
                leaders.Where(l => !string.IsNullOrEmpty(l.Name))
                        .ToDictionary(l => l.NameTextId, l => l.Name);
        heroDropdownController.FallbackText = "Random Warlord";
        heroDropdownController.AvailableHeroes = heroOptions;
        heroDropdownController.HeadshotImage.gameObject.SetActive(false);

        SetHumanPlayersDropdown();
        // Default to 1 human (index 0)
        totalHumansDropdown.value = 0;
    }
}
