#include "PathFollowingEditor.hpp"
#include <imgui.h>

bool PathFollowingEditor::renderComponent(flecs::entity entity,
					  PathFollowingComponent &pf)
{
	(void)entity;
	bool modified = false;
	ImGui::PushID("PathFollowing");

	// Current state display
	ImGui::Text("Current State: %s", pf.currentLocomotionState.c_str());
	ImGui::Separator();

	// Path following states
	ImGui::Text("Animation States:");
	int removeStateIdx = -1;
	for (int i = 0; i < (int)pf.pathFollowingStates.size(); i++) {
		auto &pfState = pf.pathFollowingStates[i];
		ImGui::PushID(i);

		char buf[256];
		snprintf(buf, sizeof(buf), "%s", pfState.name.c_str());
		if (ImGui::InputText("Name", buf, sizeof(buf))) {
			pfState.name = buf;
			modified = true;
		}

		ImGui::Indent();
		int removePairIdx = -1;
		for (int j = 0; j < (int)pfState.stateMachineStates.size(); j++) {
			auto &pair = pfState.stateMachineStates[j];
			ImGui::PushID(j);

			char smBuf[128];
			char stateBuf[128];
			snprintf(smBuf, sizeof(smBuf), "%s", pair.first.c_str());
			snprintf(stateBuf, sizeof(stateBuf), "%s",
				 pair.second.c_str());

			ImGui::SetNextItemWidth(120.0f);
			if (ImGui::InputText("##sm", smBuf, sizeof(smBuf))) {
				pair.first = smBuf;
				modified = true;
			}
			ImGui::SameLine();
			ImGui::Text("->");
			ImGui::SameLine();
			ImGui::SetNextItemWidth(120.0f);
			if (ImGui::InputText("##state", stateBuf,
					     sizeof(stateBuf))) {
				pair.second = stateBuf;
				modified = true;
			}
			ImGui::SameLine();
			if (ImGui::SmallButton("X")) {
				removePairIdx = j;
			}
			ImGui::PopID();
		}

		if (removePairIdx >= 0) {
			pfState.stateMachineStates.erase(
				pfState.stateMachineStates.begin() +
				removePairIdx);
			modified = true;
		}

		if (ImGui::SmallButton("+ Add Pair")) {
			pfState.stateMachineStates.push_back({ "main", "Idle" });
			modified = true;
		}

		if (pf.pathFollowingStates.size() > 1) {
			if (ImGui::SmallButton("Remove State")) {
				removeStateIdx = i;
				modified = true;
			}
		}
		ImGui::Unindent();
		ImGui::Separator();
		ImGui::PopID();
	}

	if (removeStateIdx >= 0) {
		pf.pathFollowingStates.erase(
			pf.pathFollowingStates.begin() + removeStateIdx);
	}

	if (ImGui::Button("Add State")) {
		pf.pathFollowingStates.push_back(PathFollowingState("new_state"));
		modified = true;
	}

	ImGui::Separator();
	ImGui::DragFloat("Walk Speed", &pf.walkSpeed, 0.1f, 0.5f, 20.0f);
	ImGui::DragFloat("Run Speed", &pf.runSpeed, 0.1f, 0.5f, 20.0f);
	if (ImGui::Checkbox("Use Root Motion", &pf.useRootMotion))
		modified = true;

	ImGui::PopID();
	return modified;
}
