#include "LodEditor.hpp"
#include "../components/LodSettings.hpp"
#include <imgui.h>
#include <vector>
#include <string>

void LodEditor::resolveSettingsEntity(LodComponent& lod)
{
	// If we have a settingsId but no valid entity, try to resolve it
	if (!lod.settingsId.empty() && !lod.hasValidSettings()) {
		// This would need access to the world to query - handled in renderSettingsSelector
	}
}

void LodEditor::renderSettingsSelector(flecs::entity entity, LodComponent& lod)
{
	// Get the world from the entity
	flecs::world world = entity.world();
	
	// Collect all entities with LodSettingsComponent
	std::vector<flecs::entity> settingsEntities;
	std::vector<std::string> settingsIds;
	std::vector<std::string> displayNames;
	int currentIndex = -1;
	
	world.query<LodSettingsComponent>().each([&](flecs::entity e, LodSettingsComponent& settings) {
		settingsEntities.push_back(e);
		settingsIds.push_back(settings.settingsId);
		
		// Build display name
		std::string displayName = settings.settingsId;
		if (displayName.empty()) {
			displayName = "LOD Settings " + std::to_string(e.id());
		}
		displayNames.push_back(displayName);
		
		// Check if this is the currently selected settings
		if (settings.settingsId == lod.settingsId) {
			currentIndex = static_cast<int>(settingsEntities.size()) - 1;
			lod.settingsEntity = e;  // Update runtime reference
		}
	});
	
	if (settingsEntities.empty()) {
		ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "No LOD Settings entities found!");
		ImGui::Text("Create an entity with LOD Settings component first.");
		return;
	}
	
	// Build combo items string (null-terminated)
	std::string comboItems;
	for (size_t i = 0; i < displayNames.size(); i++) {
		if (i > 0) comboItems += '\0';
		comboItems += displayNames[i];
	}
	comboItems += '\0';
	
	// Show "None" if no selection
	if (currentIndex < 0) {
		// Try to find by entity reference as fallback
		for (size_t i = 0; i < settingsEntities.size(); i++) {
			if (settingsEntities[i] == lod.settingsEntity) {
				currentIndex = static_cast<int>(i);
				lod.settingsId = settingsIds[i];  // Update ID from entity
				break;
			}
		}
		
		// If still not found, show -1 (None)
		if (currentIndex < 0) {
			// Prepend "None" option
			comboItems = "None\0" + comboItems;
			currentIndex = 0;
		}
	}
	
	int newIndex = currentIndex;
	if (ImGui::Combo("LOD Settings", &newIndex, comboItems.c_str())) {
		if (newIndex >= 0 && newIndex < static_cast<int>(settingsEntities.size())) {
			lod.settingsId = settingsIds[newIndex];
			lod.settingsEntity = settingsEntities[newIndex];
			lod.markDirty();
		} else if (newIndex == 0 && currentIndex < 0) {
			// Selected "None"
			lod.settingsId.clear();
			lod.settingsEntity = flecs::entity::null();
			lod.markDirty();
		}
	}
	
	// Show info about selected settings
	if (lod.hasValidSettings()) {
		const auto& settings = lod.settingsEntity.get<LodSettingsComponent>();
		ImGui::Text("Levels: %zu", settings.lodLevels.size());
		ImGui::Text("Strategy: %s", 
			settings.strategy == LodSettingsComponent::Strategy::Distance ? "Distance" :
			settings.strategy == LodSettingsComponent::Strategy::PixelCount ? "Pixel Count" : "Edge Pixel");
	}
	
	// Show the persistent ID
	if (!lod.settingsId.empty()) {
		ImGui::TextDisabled("Settings ID: %s", lod.settingsId.c_str());
	}
}

bool LodEditor::renderComponent(flecs::entity entity, LodComponent &lod)
{
	bool modified = false;

	if (ImGui::CollapsingHeader("LOD", ImGuiTreeNodeFlags_DefaultOpen)) {
		ImGui::Indent();
		
		// Settings selector with combo box
		renderSettingsSelector(entity, lod);
		
		ImGui::Separator();
		
		// Distance multiplier
		if (ImGui::DragFloat("Distance Multiplier", &lod.distanceMultiplier, 0.1f, 0.1f, 10.0f)) {
			lod.markDirty();
			modified = true;
		}
		ImGui::SetItemTooltip("Scales all LOD distances for this entity");
		
		ImGui::Separator();
		
		// Status
		if (lod.lodApplied) {
			ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), "LOD Applied");
			ImGui::Text("Settings Version: %u", lod.appliedVersion);
		} else {
			ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.0f, 1.0f), "LOD Not Applied");
		}
		
		if (lod.dirty) {
			ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.0f, 1.0f), "(update pending)");
		}
		
		// Force regenerate button
		if (ImGui::Button("Force Regenerate LOD")) {
			lod.markDirty();
			modified = true;
		}
		
		ImGui::Unindent();
	}

	return modified;
}
