#ifndef TRANSFORMEDITOR_HPP
#define TRANSFORMEDITOR_HPP
#pragma once
#include "ComponentEditorRegistry.hpp"
#include "../components/Transform.hpp"
#include "../components/EulerUtils.hpp"
#include <imgui.h>
#include <Ogre.h>
#include <functional>
#include <memory>

class TransformEditor : public ComponentEditor<TransformComponent> {
public:
    TransformEditor(Ogre::Vector3& cursorPos, std::function<void()> onCursorSet)
        : m_cursorPosition(cursorPos), m_onCursorSet(onCursorSet) {}

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

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

            // Position editing
            float pos[3] = {transform.position.x, transform.position.y, transform.position.z};
            if (ImGui::DragFloat3("Position", pos, 0.1f)) {
                transform.position = Ogre::Vector3(pos[0], pos[1], pos[2]);
                transform.applyToNode();
                modified = true;
            }

            // Rotation editing using Euler angles
            Ogre::Vector3 euler = EulerUtils::toEulerDegrees(transform.orientation);
            float rot[3] = {euler.x, euler.y, euler.z};

            if (ImGui::DragFloat3("Rotation (deg)", rot, 1.0f, -180.0f, 180.0f)) {
                transform.orientation = EulerUtils::fromEulerDegrees(Ogre::Vector3(rot[0], rot[1], rot[2]));
                transform.applyToNode();
                modified = true;
            }

            // Scale editing
            float scale[3] = {transform.scale.x, transform.scale.y, transform.scale.z};
            if (ImGui::DragFloat3("Scale", scale, 0.1f, 0.01f, 100.0f)) {
                transform.scale = Ogre::Vector3(scale[0], scale[1], scale[2]);
                transform.applyToNode();
                modified = true;
            }

            ImGui::Separator();

            // Reset button
            if (ImGui::Button("Reset Transform")) {
                transform.position = Ogre::Vector3::ZERO;
                transform.orientation = Ogre::Quaternion::IDENTITY;
                transform.scale = Ogre::Vector3::UNIT_SCALE;
                transform.applyToNode();
                modified = true;
            }

            ImGui::SameLine();

            // 3D Cursor controls
            if (ImGui::Button("Set Cursor from Position")) {
                m_cursorPosition = transform.position;
                if (m_onCursorSet) m_onCursorSet();
            }

            ImGui::SameLine();
            if (ImGui::Button("Set Position from Cursor")) {
                transform.position = m_cursorPosition;
                transform.applyToNode();
                modified = true;
            }

            ImGui::Unindent();
        }

        return modified;
    }

private:
    Ogre::Vector3& m_cursorPosition;
    std::function<void()> m_onCursorSet;
};
#endif // TRANSFORMEDITOR_HPP
