#ifndef RENDERABLEEDITOR_HPP
#define RENDERABLEEDITOR_HPP
#pragma once
#include "ComponentEditorRegistry.hpp"
#include "../components/Transform.hpp"
#include <imgui.h>
#include <Ogre.h>
#include <string>
#include <memory>

class RenderableEditor : public ComponentEditor<RenderableComponent> {
public:
    RenderableEditor(Ogre::SceneManager* sceneMgr) : m_sceneMgr(sceneMgr) {}

protected:
    bool renderComponent(flecs::entity entity, RenderableComponent& renderable) override {
        bool modified = false;

        if (ImGui::CollapsingHeader("Renderable", ImGuiTreeNodeFlags_DefaultOpen)) {
            ImGui::Indent();

            // Mesh selection
            static char meshName[128] = "";
            ImGui::InputText("Mesh Name", meshName, sizeof(meshName));

            if (ImGui::Button("Load Mesh")) {
                if (strlen(meshName) > 0) {
                    if (renderable.entity) {
                        m_sceneMgr->destroyEntity(renderable.entity);
                    }

                    renderable.meshName = meshName;
                    try {
                        renderable.entity = m_sceneMgr->createEntity(meshName);

                        // Attach to scene node if transform exists
                        if (entity.has<TransformComponent>()) {
                            auto& transform = entity.get_mut<TransformComponent>();
                            if (transform.node) {
                                transform.node->attachObject(renderable.entity);
                            }
                        }

                        modified = true;
                    } catch (const std::exception& e) {
                        Ogre::LogManager::getSingleton().logMessage(
                            "Failed to load mesh: " + std::string(e.what())
                        );
                    }
                }
            }

            // Show current mesh info
            if (!renderable.meshName.empty()) {
                ImGui::Text("Current Mesh: %s", renderable.meshName.c_str());
            }

            // Detach button
            if (renderable.entity && ImGui::Button("Detach Mesh")) {
                if (entity.has<TransformComponent>()) {
                    auto& transform = entity.get_mut<TransformComponent>();
                    if (transform.node) {
                        transform.node->detachObject(renderable.entity);
                    }
                }
                m_sceneMgr->destroyEntity(renderable.entity);
                renderable.entity = nullptr;
                renderable.meshName.clear();
                modified = true;
            }

            ImGui::Unindent();
        }

        return modified;
    }

private:
    Ogre::SceneManager* m_sceneMgr;
};
#endif // RENDERABLEEDITOR_HPP
