using Dalamud.Bindings.ImGui;
using Dalamud.Interface.Utility;
using LightlessSync.API.Dto.Group;
using LightlessSync.UI.Handlers;

using System.Numerics;

namespace LightlessSync.UI.Components;

public class SelectSyncshellForTagUi
{
    private readonly TagHandler _tagHandler;
    private string _filter = string.Empty;
    private bool _opened = false;
    private HashSet<string> _syncshellsInGroup = new(StringComparer.Ordinal);
    private bool _show = false;
    private string _tag = string.Empty;

    public SelectSyncshellForTagUi(TagHandler tagHandler)
    {
        _tagHandler = tagHandler;
    }

    public void Draw(IReadOnlyCollection<GroupFullInfoDto> groups)
    {
        var workHeight = ImGui.GetMainViewport().WorkSize.Y / ImGuiHelpers.GlobalScale;
        var minSize = new Vector2(300, workHeight < 400 ? workHeight : 400) * ImGuiHelpers.GlobalScale;
        var maxSize = new Vector2(300, 1000) * ImGuiHelpers.GlobalScale;

        var popupName = $"Choose Syncshells for Group {_tag}";

        if (!_show)
        {
            _opened = false;
        }

        if (_show && !_opened)
        {
            ImGui.SetNextWindowSize(minSize);
            UiSharedService.CenterNextWindow(minSize.X, minSize.Y, ImGuiCond.Always);
            ImGui.OpenPopup(popupName);
            _opened = true;
        }

        ImGui.SetNextWindowSizeConstraints(minSize, maxSize);
        if (ImGui.BeginPopupModal(popupName, ref _show, ImGuiWindowFlags.Popup | ImGuiWindowFlags.Modal))
        {
            ImGui.TextUnformatted($"Select syncshells for group {_tag}");

            ImGui.InputTextWithHint("##filter", "Filter", ref _filter, 255, ImGuiInputTextFlags.None);
            foreach (var group in groups
                .Where(g => string.IsNullOrEmpty(_filter) || g.GID.Contains(_filter, StringComparison.OrdinalIgnoreCase))
                .OrderBy(g => g.GroupAliasOrGID, StringComparer.OrdinalIgnoreCase)
                .ToList())
            {
                var isInGroup = _syncshellsInGroup.Contains(group.GID);
                if (ImGui.Checkbox(group.GroupAliasOrGID, ref isInGroup))
                {
                    if (isInGroup)
                    {
                        _tagHandler.AddTagToSyncshell(group.GID, _tag);
                        _syncshellsInGroup.Add(group.GID);
                    }
                    else
                    {
                        _tagHandler.RemoveTagFromSyncshell(group.GID, _tag);
                        _syncshellsInGroup.Remove(group.GID);
                    }
                }
            }
            ImGui.EndPopup();
        }
        else
        {
            _filter = string.Empty;
            _show = false;
        }
    }

    public void Open(string tag)
    {
        _syncshellsInGroup = _tagHandler.GetOtherSyncshellsForTag(tag);
        _tag = tag;
        _show = true;
    }
}