#include "GoapRunnerEditor.hpp"
#include "../components/GoapPlanner.hpp"
#include <imgui.h>

const char *GoapRunnerEditor::stateName(GoapRunnerComponent::State state)
{
	switch (state) {
	case GoapRunnerComponent::State::Idle:
		return "Idle";
	case GoapRunnerComponent::State::RunningAction:
		return "Running Action";
	case GoapRunnerComponent::State::MovingToSmartObject:
		return "Moving to Smart Object";
	case GoapRunnerComponent::State::ExecutingSmartObject:
		return "Executing Smart Object";
	case GoapRunnerComponent::State::PlanComplete:
		return "Plan Complete";
	}
	return "Unknown";
}

bool GoapRunnerEditor::renderComponent(flecs::entity entity,
					       GoapRunnerComponent &runner)
{
	bool modified = false;
	ImGui::PushID("GoapRunner");

	ImGui::Text("State: %s", stateName(runner.state));
	ImGui::Text("Action Index: %d", runner.currentActionIndex);
	if (!runner.currentActionName.empty()) {
		ImGui::Text("Current Action: %s",
			    runner.currentActionName.c_str());
	}
	if (runner.targetSmartObjectId != 0) {
		ImGui::Text("Target Smart Object: %llu",
			    (unsigned long long)runner.targetSmartObjectId);
	}

	if (ImGui::Checkbox("Auto Replan", &runner.autoReplan))
		modified = true;

	ImGui::Separator();

	// Display active plan
	if (!runner.planActions.empty()) {
		ImGui::Text("Active Plan (%zu actions):",
			    runner.planActions.size());
		ImGui::Indent();
		for (int i = 0; i < (int)runner.planActions.size(); i++) {
			bool isCurrent = (i == runner.currentActionIndex);
			if (isCurrent) {
				ImGui::TextColored(ImVec4(0, 1, 0, 1),
						   "-> %d. %s", i + 1,
						   runner.planActions[i].c_str());
			} else {
				ImGui::Text("   %d. %s", i + 1,
					    runner.planActions[i].c_str());
			}
		}
		ImGui::Unindent();
	} else {
		ImGui::TextDisabled("No active plan.");
	}

	// Display plan queue
	if (entity.has<GoapPlannerComponent>()) {
		auto &planner = entity.get<GoapPlannerComponent>();
		if (!planner.planQueue.empty()) {
			ImGui::Separator();
			ImGui::Text("Plan Queue (%zu plans):",
				    planner.planQueue.size());
			ImGui::Indent();
			for (int p = 0;
			     p < (int)planner.planQueue.size(); p++) {
				const auto &plan = planner.planQueue[p];
				ImGui::Text("Plan %d: cost=%d, %zu actions",
					    p + 1, plan.totalCost,
					    plan.actions.size());
			}
			ImGui::Unindent();
		}
	}

	// Manual controls
	if (runner.state != GoapRunnerComponent::State::Idle) {
		ImGui::Separator();
		if (ImGui::Button("Stop")) {
			runner.state = GoapRunnerComponent::State::Idle;
			runner.currentActionIndex = 0;
			runner.currentActionName.clear();
			runner.targetSmartObjectId = 0;
			runner.planActions.clear();
			modified = true;
		}
	}

	ImGui::PopID();
	return modified;
}
