using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;

public class BattleSetupMenuUI : MonoBehaviour
{
    public VisualTreeAsset characterEntryTemplate; // Assign in the inspector
    private List<VisualElement> playerEntries = new();
    private List<VisualElement> enemyEntries = new();

    private VisualElement root;
    private Button startButton;

    void OnEnable()
    {
        root = GetComponent<UIDocument>().rootVisualElement;

        var playerList = root.Q<ScrollView>("PlayerList");
        var enemyList = root.Q<ScrollView>("EnemyList");
        var addPlayerButton = root.Q<Button>("AddPlayerButton");
        var addEnemyButton = root.Q<Button>("AddEnemyButton");
        startButton = root.Q<Button>("StartBattleButton");

        addPlayerButton.clicked += () => AddCharacterEntry(playerList, true);
        addEnemyButton.clicked += () => AddCharacterEntry(enemyList, false);
        startButton.clicked += StartBattle;

        UpdateStartButton();
    }

    void AddCharacterEntry(ScrollView list, bool isPlayer)
    {
        var entry = characterEntryTemplate.Instantiate();
        var nameText = entry.Q<TextField>("CharacterName");
        var weaponDropdown = entry.Q<DropdownField>("WeaponDropdown");
        var removeButton = entry.Q<Button>("RemoveButton");

        nameText.value = isPlayer ? "Player" : "Enemy";
        weaponDropdown.choices = new List<string> { "Sword", "Bow" };
        weaponDropdown.value = "Sword";

        removeButton.clicked += () =>
        {
            list.Remove(entry);
            if (isPlayer) playerEntries.Remove(entry);
            else enemyEntries.Remove(entry);
            UpdateStartButton();
        };
        list.Add(entry);
        if (isPlayer) playerEntries.Add(entry);
        else enemyEntries.Add(entry);
        UpdateStartButton();
    }

    void UpdateStartButton()
    {
        startButton.SetEnabled(playerEntries.Count > 0 && enemyEntries.Count > 0);
    }

    void StartBattle()
    {
        BattleSetupData.playerSelections.Clear();
        BattleSetupData.enemySelections.Clear();

        foreach (var entry in playerEntries)
        {
            BattleSetupData.playerSelections.Add(GetSelectionFromEntry(entry, true));
        }
        foreach (var entry in enemyEntries)
        {
            BattleSetupData.enemySelections.Add(GetSelectionFromEntry(entry, false));
        }

        SceneManager.LoadScene("BattleScene");
    }

    CharacterSelection GetSelectionFromEntry(VisualElement entry, bool isPlayer)
    {
        var dropdown = entry.Q<DropdownField>("WeaponDropdown");
        var nameText = entry.Q<TextField>("CharacterName");
        return new CharacterSelection
        {
            characterName = nameText.value,
            weaponType = dropdown.value
        };
    }
}
