#pragma once
#include "../component.h"
#include "Lua/lua.hpp"
#include <string>
#include <fstream>
#include <sstream>
#include <imgui.h>
#include <filesystem>

namespace ecs {

class LuaScriptComponent : public Component {
public:
    LuaScriptComponent() : scriptCreated(false), popupOpen(true) {
        L = luaL_newstate();
        luaL_openlibs(L);
    }

    ~LuaScriptComponent() override {
        if (L) {
            lua_close(L);
            L = nullptr;
        }
    }

    void OnImGuiRender() override {
        if (popupOpen) {
            ImGui::OpenPopup("Nouveau Script Lua");
            if (ImGui::BeginPopupModal("Nouveau Script Lua", NULL, ImGuiWindowFlags_AlwaysAutoResize)) {
                
                ImGui::InputText("Nom du Script", scriptNameBuffer, sizeof(scriptNameBuffer));

                if (ImGui::Button("Annuler")) {
                    scriptCreated = false;
                    popupOpen = false;
                    // Signal pour retirer ce component (à gérer par l'entity)
                }
                ImGui::SameLine();
                if (ImGui::Button("Valider")) {
                    if (CreateScriptFile()) {
                        scriptCreated = true;
                        popupOpen = false;
                    } else {
                        // Gestion d'erreur possible (imprimer popup message)
                    }
                }
                ImGui::EndPopup();
            }
        }

        if (scriptCreated) {
            ImGui::TextWrapped("Script associe: %s", scriptName.c_str());
        }
    }

    bool HasScript() const { return scriptCreated; }
    const std::string& GetScriptName() const { return scriptName; }

private:
    lua_State* L = nullptr;
    char scriptNameBuffer[128] = {0};
    std::string scriptName;
    bool scriptCreated = false;
    bool popupOpen = false;

    bool CreateScriptFile() {
        if (strlen(scriptNameBuffer) == 0)
            R_FALSE

        scriptName = scriptNameBuffer;
        if (scriptName.length() < 4 || scriptName.substr(scriptName.length() - 4) != ".lua") {
            scriptName += ".lua";
        }

        // Dossier standard des scripts
        std::string execFolder = std::filesystem::current_path().string();
        std::string scriptFolder = execFolder + "/assets/Script/";

        // Créer dossiers s'ils manquent
        std::error_code ec;
        std::filesystem::create_directories(scriptFolder, ec);
        if (ec) {
            // Log erreur
            R_FALSE
        }

        std::string fullPath = scriptFolder + scriptName;

        // Créer un fichier script vide ou template simple
        std::ofstream ofs(fullPath);
        if (!ofs) R_FALSE

        ofs << "-- Script Lua vide pour ECS\n\nfunction on_update(dt)\n  -- Code ici\nend\n";
        ofs.close();

        R_TRUE
    }
};

}  // namespace ecs
