#include "ItemEditor.hpp"
#include "../components/ActionDatabase.hpp"
#include <imgui.h>

bool ItemEditor::renderComponent(flecs::entity entity, ItemComponent &item)
{
	(void)entity;
	bool modified = false;
	ImGui::PushID("Item");

	ImGui::Text("Item Settings");
	ImGui::Separator();

	// Item name
	char nameBuf[256];
	strncpy(nameBuf, item.itemName.c_str(), sizeof(nameBuf));
	nameBuf[sizeof(nameBuf) - 1] = '\0';
	if (ImGui::InputText("Name", nameBuf, sizeof(nameBuf))) {
		item.itemName = nameBuf;
		modified = true;
	}

	// Item type
	char typeBuf[256];
	strncpy(typeBuf, item.itemType.c_str(), sizeof(typeBuf));
	typeBuf[sizeof(typeBuf) - 1] = '\0';
	if (ImGui::InputText("Type", typeBuf, sizeof(typeBuf))) {
		item.itemType = typeBuf;
		modified = true;
	}

	// Item ID
	char idBuf[256];
	strncpy(idBuf, item.itemId.c_str(), sizeof(idBuf));
	idBuf[sizeof(idBuf) - 1] = '\0';
	if (ImGui::InputText("Item ID", idBuf, sizeof(idBuf))) {
		item.itemId = idBuf;
		modified = true;
	}

	// Stack size
	int stackSize = item.stackSize;
	if (ImGui::DragInt("Stack Size", &stackSize, 1, 1, 999)) {
		if (stackSize < 1)
			stackSize = 1;
		item.stackSize = stackSize;
		modified = true;
	}

	// Max stack size
	int maxStack = item.maxStackSize;
	if (ImGui::DragInt("Max Stack", &maxStack, 1, 1, 999)) {
		if (maxStack < 1)
			maxStack = 1;
		item.maxStackSize = maxStack;
		modified = true;
	}

	// Weight
	if (ImGui::DragFloat("Weight", &item.weight, 0.01f, 0.0f, 100.0f,
			     "%.2f")) {
		if (item.weight < 0.0f)
			item.weight = 0.0f;
		modified = true;
	}

	// Value
	if (ImGui::DragInt("Value", &item.value, 1, 0, 99999)) {
		if (item.value < 0)
			item.value = 0;
		modified = true;
	}

	ImGui::Separator();
	ImGui::Text("Use Action");

	// Use action name
	char useBuf[256];
	strncpy(useBuf, item.useActionName.c_str(), sizeof(useBuf));
	useBuf[sizeof(useBuf) - 1] = '\0';
	if (ImGui::InputText("Use Action", useBuf, sizeof(useBuf))) {
		item.useActionName = useBuf;
		modified = true;
	}

	// Pick from action database singleton
	ActionDatabase *db = ActionDatabase::getSingletonPtr();

	if (db && !db->actions.empty()) {
		static int selectedAction = -1;
		std::vector<const char *> availableNames;
		std::vector<Ogre::String> availableNamesStorage;

		for (const auto &action : db->actions) {
			availableNamesStorage.push_back(action.name);
			availableNames.push_back(
				availableNamesStorage.back().c_str());
		}

		if (!availableNames.empty()) {
			if (selectedAction >= (int)availableNames.size())
				selectedAction = 0;
			ImGui::SameLine();
			if (ImGui::Combo("##useActionSelect", &selectedAction,
					 availableNames.data(),
					 (int)availableNames.size())) {
			}
			ImGui::SameLine();
			if (ImGui::Button("Set")) {
				if (selectedAction >= 0 &&
				    selectedAction <
					    (int)availableNames.size()) {
					item.useActionName =
						availableNamesStorage
							[selectedAction];
					modified = true;
				}
			}
		}
	}

	ImGui::PopID();
	return modified;
}
