#include "MainMenuState.h"
#include "GamePlayState.h"
#include "AssetEditorState.h"
#include "MapEditorState.h"
#include "../Engine.h"
#include <imgui.h>
#include <SDL2/SDL_log.h>

void MainMenuState::Enter(Engine& engine)
{
    fadeAlpha = 1.0f;
}

void MainMenuState::Exit(Engine& engine)
{
}

void MainMenuState::HandleEvents(Engine& engine, SDL_Event& e)
{
}

void MainMenuState::Update(Engine& engine, float dt)
{
    if (fadeAlpha < 1.0f)
    {
        fadeAlpha += dt * 2.0f;
        if (fadeAlpha > 1.0f)
        {
            fadeAlpha = 1.0f;
        }
    }
}

void MainMenuState::Render(Engine& engine)
{
    SDL_Renderer* renderer = engine.GetRenderer();
    SDL_SetRenderDrawColor(renderer, 10, 20, 40, 255);
    SDL_RenderClear(renderer);
}

void MainMenuState::RenderImGui(Engine& engine)
{
    ImGuiIO& io = ImGui::GetIO();
    
    ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f),
                                   ImGuiCond_Always,
                                   ImVec2(0.5f, 0.5f));
    ImGui::SetNextWindowSize(ImVec2(400, 500), ImGuiCond_FirstUseEver);
    
    ImGui::Begin("Main Menu", nullptr, ImGuiWindowFlags_NoTitleBar |
                                       ImGuiWindowFlags_NoResize |
                                       ImGuiWindowFlags_NoMove |
                                       ImGuiWindowFlags_NoCollapse);
    ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[0]);
    ImGui::Dummy(ImVec2(0, 40));
    ImGui::SetCursorPosX((ImGui::GetWindowSize().x - ImGui::CalcTextSize("kariokaEngine").x) * 0.5f);
    ImGui::TextColored(ImVec4(0.9f, 0.9f, 1.0f, fadeAlpha), "kariokaEngine");

    // Main Menu Buttons
    ImGui::Dummy(ImVec2(0.0f, 100.0f));
    
    float buttonWidth = 200.f;
    float windowWidth = ImGui::GetWindowSize().x;

    ImGui::SetCursorPosX((windowWidth - buttonWidth) * 0.5f);
    if (ImGui::Button("Enter World", ImVec2(buttonWidth, 30)))
    {
        // engine.stateManager.ChangeState(std::make_unique<GamePlayState>(), engine);
        engine.stateManager.PushState(std::make_unique<GamePlayState>(), engine);
    }
    
    ImGui::SetCursorPosX((windowWidth - buttonWidth) * 0.5f);
    if (ImGui::Button("Map Editor", ImVec2(buttonWidth, 30)))
    {
        engine.stateManager.PushState(std::make_unique<MapEditorState>(), engine);
    }
    
    ImGui::SetCursorPosX((windowWidth - buttonWidth) * 0.5f);
    if (ImGui::Button("Asset Editor", ImVec2(buttonWidth, 30)))
    {
        engine.stateManager.PushState(std::make_unique<AssetEditorState>(), engine);
    }
    
    ImGui::SetCursorPosX((windowWidth - buttonWidth) * 0.5f);
    if (ImGui::Button("Exit", ImVec2(buttonWidth, 30)))
    {
        engine.StopRunning();
    }
    
    ImGui::PopFont();
    ImGui::End();
}
