//
// Created by sebastian on 06.08.26.
//

#include "MainMenuUiLayer.h"

#include "imgui.h"
#include "GLFW/glfw3.h"
#include "multiplayer/lobby/LobbyScene.h"
#include "spdlog/spdlog.h"

void MainMenuUiLayer::onRender() {
    Layer::onRender();

    std::vector<engine::GUITexture> guiElements;
    guiElements.emplace_back(*backgroundImage);
    m_guiRenderer.render(guiElements);

    // Imgui Main Menu
    ImGui::SetNextWindowPos(ImVec2(20, 20), ImGuiCond_FirstUseEver);
    ImGui::Begin("Ludo", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize);

    //ImGui::PushFont(titleFont); // falls du einen größeren Font geladen hast, sonst weglassen
    ImGui::Text("Ludo");

    ImGui::Separator();
    ImGui::Spacing();

    const ImVec2 buttonSize(180, 40);

    if (ImGui::Button("Neues Spiel", buttonSize)) {
        // z.B. State-Wechsel: game.setState(GameState::Playing);
    }

    ImGui::Spacing();

    ImGui::Spacing();

    if (ImGui::Button("Multiplayer", buttonSize)) {
        spdlog::info("Open Multiplayer Modal");
        ImGui::OpenPopup("ConnectToServer");
    }

    ImGui::Spacing();

    ImGui::Spacing();

    if (ImGui::Button("Quit", buttonSize)) {
        ApplicationEvents e = QuitRequested{};
        m_applicationEventBus->publish(e);
    }

    renderConnectDialog();

    ImGui::End();


}

void MainMenuUiLayer::onAttachImpl() {
    Layer::onAttachImpl();

    auto backgroundTexture = m_assetManager.getTexture("main_menu_background");

    backgroundImage = std::make_unique<engine::GUITexture>(backgroundTexture, glm::vec2(0,0), glm::vec2(1,1));

    m_networkEventBus->subscribe([this](NetworkEvents& event) {
        std::visit([this](auto&& e) {
            using T = std::decay_t<decltype(e)>;
            if constexpr (std::is_same_v<T, ConnectResult>) {
                if (e.success) {
                    spdlog::info("Received positive Connection Result");
                    m_connectionError = false;
                    std::unique_ptr<LobbyScene> lobbyScene = std::make_unique<LobbyScene>(m_applicationEventBus, getInputStack(), getKeyboard(), getMouse());

                } else {
                    spdlog::info("Received negative Connection Result");
                    m_connectionError = true;
                    m_errorMessage = e.errorMessage;
                }
            }
        }, event);
    });
}

void MainMenuUiLayer::onDetachImpl() {
    Layer::onDetachImpl();
}

void MainMenuUiLayer::renderConnectDialog() {
    // Zentriert öffnen
    ImVec2 center = ImGui::GetMainViewport()->GetCenter();
    ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));

    if (ImGui::BeginPopupModal("ConnectToServer", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
        if (m_closeConnectPopup) {
            ImGui::CloseCurrentPopup();
        }
        ImGui::InputText("Host", m_hostBuffer, sizeof(m_hostBuffer));
        ImGui::InputInt("Port", &m_port);

        if (m_connectionError) {
            ImGui::TextColored(ImVec4(1, 0.3f, 0.3f, 1), "%s", m_errorMessage.c_str());
        }

        ImGui::Spacing();

        if (ImGui::Button("Connect", ImVec2(120, 0))) {
            // ApplicationEvents::ConnectRequested e{ m_hostBuffer, static_cast<uint16_t>(m_port) };
            // m_appEvents.publish(e);
            // Popup offen lassen bis Ergebnis feststeht, siehe unten
            NetworkEvents connectRequest = ConnectRequest(m_hostBuffer, static_cast<uint16_t>(m_port));
            m_networkEventBus->publish(connectRequest);
        }

        ImGui::SameLine();

        if (ImGui::Button("Cancel", ImVec2(120, 0))) {
            ImGui::CloseCurrentPopup();
        }

        ImGui::EndPopup();
    }
}

void MainMenuUiLayer::onUpdate(float deltaTime) {
    Layer::onUpdate(deltaTime);
}
