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 AvailableGameItem : MonoBehaviour {
    public GameObject item;
    public TextMeshProUGUI gameIdField;
    public HeroDropdownController heroDropdownController;
    public TextMeshProUGUI playerCountField;
    public Button joinButton;
    public TextMeshProUGUI buttonText;
    public Button dropButton;

    public Action<long, string> JoinCallback;
    public Action<long> DropCallback;

    private List<AvailableLeader> availableLeaders;
    private long gameId;
    private int maxHumanPlayerCount;

    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 JoinClicked() { JoinCallback(gameId, SelectedLeaderTextId); }

    public void DropClicked() { DropCallback?.Invoke(gameId); }

    public void SetAvailableNewGame(
            long gameId,
            string playersString,
            List<AvailableLeader> leaders,
            int maxHumanPlayerCount) {
        availableLeaders = leaders;
        this.gameId = gameId;
        this.maxHumanPlayerCount = maxHumanPlayerCount;

        gameIdField.text = string.Format("{0:X}", gameId);
        playerCountField.text = playersString;
        joinButton.interactable = true;
        buttonText.text = "JOIN";

        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
            });
        }

        // 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";
        heroDropdownController.AvailableHeroes = heroOptions;
    }
}
