#include "LuaGlobals.h"
#include "../../core/scripts/LuaGlobalBridge.h"
#include "../../core/utils/Logging.h"
#include "../../core/utils/EngineConfig.h"
#include <imgui.h>

#include "LuaGlobals.h"
#include "../../core/scripts/LuaGlobalBridge.h"
#include "../../core/utils/Logging.h"
#include "../../core/utils/EngineConfig.h"
#include <imgui.h>

void DrawImGuiWindow()
{
    if (!g_engineConfig.settings.show_lua_globals_window)
        return;

    auto allGlobals = LuaGlobalBridge::GetAll();

    ImGui::Begin("Lua Globals", nullptr, ImGuiWindowFlags_AlwaysAutoResize);

    if (allGlobals.empty())
    {
        ImGui::TextDisabled("No global variables set.");
    }
    else
    {
        ImGui::Text("Active Globals");
        ImGui::Separator();

        ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(6, 4));
        ImGui::PushStyleColor(ImGuiCol_TableHeaderBg, ImVec4(0.15f, 0.18f, 0.22f, 1.0f));
        ImGui::PushStyleColor(ImGuiCol_TableBorderStrong, ImVec4(0.3f, 0.3f, 0.3f, 0.5f));

        if (ImGui::BeginTable("GlobalsTable", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable))
        {
            ImGui::TableSetupColumn("Key", ImGuiTableColumnFlags_WidthFixed, 180.0f);
            ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, 80.0f);
            ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch);
            ImGui::TableHeadersRow();

            for (const auto &[key, value] : allGlobals)
            {
                std::string typeStr;
                std::string valueStr;

                std::visit([&](auto &&val)
                           {
                    using T = std::decay_t<decltype(val)>;
                    if constexpr (std::is_same_v<T, double>) {
                        typeStr = "number";
                        valueStr = std::to_string(val);
                    }
                    else if constexpr (std::is_same_v<T, bool>) {
                        typeStr = "bool";
                        valueStr = val ? "true" : "false";
                    }
                    else if constexpr (std::is_same_v<T, std::string>) {
                        typeStr = "string";
                        valueStr = val;
                    } }, value);

                ImGui::TableNextRow();

                ImGui::TableSetColumnIndex(0);
                ImGui::Text("%s", key.c_str());

                ImGui::TableSetColumnIndex(1);
                ImGui::TextColored(ImVec4(0.7f, 0.9f, 1.0f, 1.0f), "%s", typeStr.c_str());

                ImGui::TableSetColumnIndex(2);
                ImGui::TextWrapped("%s", valueStr.c_str());
            }

            ImGui::EndTable();
        }

        ImGui::PopStyleColor(2);
        ImGui::PopStyleVar();
    }

    ImGui::End();
}
