#include "LotEditor.hpp"
#include "../components/CellGrid.hpp"
#include "../components/ProceduralTexture.hpp"
#include "../components/ProceduralMaterial.hpp"
#include <imgui.h>

bool LotEditor::renderComponent(flecs::entity entity, LotComponent& lot)
{
    bool modified = false;
    
    if (ImGui::CollapsingHeader("Lot", ImGuiTreeNodeFlags_DefaultOpen)) {
        ImGui::Indent();
        
        // Dimensions
        int dims[2] = { lot.width, lot.depth };
        if (ImGui::InputInt2("Lot Size (W/D)", dims)) {
            lot.width = std::max(4, dims[0]);
            lot.depth = std::max(4, dims[1]);
            modified = true;
        }
        
        // Position/rotation
        if (ImGui::SliderFloat("Angle (degrees)", &lot.angle, -180.0f, 180.0f)) {
            modified = true;
        }
        if (ImGui::DragFloat("Elevation", &lot.elevation, 0.1f, -10.0f, 10.0f)) {
            modified = true;
        }
        if (ImGui::DragFloat("Offset X", &lot.offsetX, 0.1f)) {
            modified = true;
        }
        if (ImGui::DragFloat("Offset Z", &lot.offsetZ, 0.1f)) {
            modified = true;
        }
        if (ImGui::SliderFloat("Friction", &lot.friction, 0.0f, 1.0f, "%.2f")) {
            modified = true;
        }
        
        // Template
        char templateName[128] = {0};
        strncpy(templateName, lot.templateName.c_str(), sizeof(templateName) - 1);
        if (ImGui::InputText("Template", templateName, sizeof(templateName))) {
            lot.templateName = templateName;
            modified = true;
        }
        
        ImGui::Separator();
        ImGui::Text("Lot Material:");
        
        // Material selector
        flecs::world world = entity.world();
        std::vector<flecs::entity> materialEntities;
        std::vector<std::string> materialNames;
        materialEntities.push_back(flecs::entity::null());
        materialNames.push_back("Use District/Town");
        
        int currentMatIndex = -1;
        world.query<ProceduralMaterialComponent>().each([&](flecs::entity e, ProceduralMaterialComponent& mat) {
            materialEntities.push_back(e);
            std::string name = mat.materialName.empty() ? "Material " + std::to_string(e.id()) : mat.materialName;
            materialNames.push_back(name);
            if (lot.proceduralMaterialEntity == e) {
                currentMatIndex = (int)materialEntities.size() - 1;
            }
        });
        
        if (currentMatIndex == -1) currentMatIndex = 0;
        
        std::string comboItems;
        for (size_t i = 0; i < materialNames.size(); ++i) {
            if (i > 0) comboItems += '\0';
            comboItems += materialNames[i];
        }
        comboItems += '\0';
        
        int newIndex = currentMatIndex;
        if (ImGui::Combo("Material", &newIndex, comboItems.c_str())) {
            if (newIndex == 0) {
                lot.proceduralMaterialEntity = flecs::entity::null();
                lot.proceduralMaterialEntityId.clear();
            } else {
                lot.proceduralMaterialEntity = materialEntities[newIndex];
                lot.proceduralMaterialEntityId = std::to_string(materialEntities[newIndex].id());
            }
            modified = true;
        }
        
        // Texture rectangle selector
        if (lot.proceduralMaterialEntity.is_alive()) {
            flecs::entity textureEntity = flecs::entity::null();
            if (lot.proceduralMaterialEntity.has<ProceduralMaterialComponent>()) {
                const auto& mat = lot.proceduralMaterialEntity.get<ProceduralMaterialComponent>();
                if (mat.diffuseTextureEntity.is_alive()) {
                    textureEntity = mat.diffuseTextureEntity;
                }
            }
            
            if (textureEntity.is_alive() && textureEntity.has<ProceduralTextureComponent>()) {
                const auto& texture = textureEntity.get<ProceduralTextureComponent>();
                const auto& namedRects = texture.getAllNamedRects();
                
                if (!namedRects.empty()) {
                    std::vector<std::string> rectNames;
                    rectNames.push_back("None (use full texture)");
                    
                    int currentRectIndex = -1;
                    for (const auto& pair : namedRects) {
                        rectNames.push_back(pair.first);
                        if (lot.textureRectName == pair.first) {
                            currentRectIndex = (int)rectNames.size() - 1;
                        }
                    }
                    
                    if (currentRectIndex == -1) currentRectIndex = 0;
                    
                    std::string rectComboItems;
                    for (size_t i = 0; i < rectNames.size(); ++i) {
                        if (i > 0) rectComboItems += '\0';
                        rectComboItems += rectNames[i];
                    }
                    rectComboItems += '\0';
                    
                    int newRectIndex = currentRectIndex;
                    if (ImGui::Combo("Texture Rectangle", &newRectIndex, rectComboItems.c_str())) {
                        if (newRectIndex == 0) {
                            lot.textureRectName.clear();
                        } else {
                            lot.textureRectName = rectNames[newRectIndex];
                        }
                        modified = true;
                    }
                }
            }
        }
        
        // Statistics
        int cellCount = 0;
        int roomCount = 0;
        int roofCount = 0;
        
        entity.children([&](flecs::entity child) {
            if (child.has<CellGridComponent>()) {
                cellCount = child.get<CellGridComponent>().cells.size();
            }
            if (child.has<RoomComponent>()) {
                roomCount++;
            }
            if (child.has<RoofComponent>()) {
                roofCount++;
            }
        });
        
        ImGui::Separator();
        ImGui::Text("Cells: %d", cellCount);
        ImGui::Text("Rooms: %d", roomCount);
        ImGui::Text("Roofs: %d", roofCount);
        
        if (modified) {
            lot.markDirty();
        }
        
        ImGui::Unindent();
    }
    
    return modified;
}
