using System;
using System.Collections.Generic;
using Sirenix.Utilities;
using UnityEngine;
using UnityEngine.UIElements;
using VOID.Generic.Objects.Unit;
using VOID.Generic.Player;
using VOID.UserInterface.Game.Party;

namespace VOID.UserInterface.Generic.Lobby
{
    public class LobbyGameStarterUI : MonoBehaviour
    {
        public static LobbyGameStarterUI current { get; private set; }
        
        // Visual Elements
        private VisualElement _rootElement;
        private VisualElement _offsetElement;
        private VisualElement _unitsElement;
        
        private Dictionary<UnitObject, UnitPortraitUI> _unitPortraits = new();

        private void Awake()
        {
            current = this;
            
            var uiDocument = gameObject.GetComponent<UIDocument>();
            var templateElement = uiDocument.rootVisualElement;

            _rootElement = templateElement.Q("root-lobby-game-starter");
            _rootElement.dataSource = this;
            
            _offsetElement = templateElement.Q("offset");
            _unitsElement = templateElement.Q("units");

            // Remove all placeholders
            _unitsElement.Clear();
            
            // Main party UI hidden because no unit selected - hide offset
            _offsetElement.style.display = DisplayStyle.None;
        }

        private void Start()
        {
            PlayerController.current.OnMainUnitChange += OnMainUnitChange;
        }

        public void AddUnit(UnitObject unit, Action<UnitObject> onSelect)
        {
            var unitPortrait = new UnitPortraitUI();
            unitPortrait.InitNew(_unitsElement);
            unitPortrait.SetUnit(unit);
            unitPortrait.OnClick += onSelect;
            _unitPortraits.Add(unit, unitPortrait);
        }
        
        private void OnMainUnitChange(UnitObject unit)
        {
            // Show all available units to select
            _unitPortraits.Values.ForEach(unitPortrait => unitPortrait.templateElement.style.display = DisplayStyle.Flex);
            
            // Hide main unit portrait, it will be displayed in party ui
            if (_unitPortraits.TryGetValue(unit, out var mainUnitPortrait))
                mainUnitPortrait.templateElement.style.display = DisplayStyle.None;
            
            // Party UI should have main unit set - show offset to prevent overlapping
            _offsetElement.style.display = DisplayStyle.Flex;
        }
    }
}