import { world, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import {
	main_menu,
	colorMap,
	upgradedMaterials,
	upgradedTools,
	materialResource,
	armorTypes,
	// armorMaterials,
	armorParts,
	armorDescriptions,
	specialItems,
	swordSetMaterials,
	swordSetSwords,
} from "./book_gld.js";

function getUpgradedToolData(type, material, tool) {
	const matName = main_menu.materialNames[material] || material;
	const toolName = tool.charAt(0).toUpperCase() + tool.slice(1);
	const resource = materialResource[material];
	if (type === "double") {
		return {
			input1: `${matName} ${toolName}`,
			input2: `2x ${resource}`,
			result: `Double ${matName} ${toolName}`,
		};
	} else if (type === "triple") {
		return {
			input1: `Double ${matName} ${toolName}`,
			input2: `2x ${resource}`,
			result: `Triple ${matName} ${toolName}`,
		};
	}
	return null;
}

async function showUpgradedToolsMaterials(player) {
	const form = new ActionFormData().title(`§l§6Upgraded Weapons & Tools§r`);
	upgradedMaterials.forEach((mat) => {
		const matName = main_menu.materialNames[mat] || mat;
		const iconPath = `textures/tcs/cwp/ui/upg_icons/double/${mat}/double_${mat}_sword`;
		form.button(`§l${colorMap[mat]}Upgraded ${matName} Tools§r`, iconPath);
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === upgradedMaterials.length) {
			showWelcomePage(player);
		} else {
			const mat = upgradedMaterials[response.selection];
			showUpgradedToolsTypeSelection(player, mat);
		}
	});
}

async function showUpgradedToolsTypeSelection(player, material) {
	const matName = main_menu.materialNames[material] || material;
	const form = new ActionFormData().title(`${colorMap[material]}§lUpgraded ${matName} Tools§r`)
	form.button(`§l${colorMap[material]}Double ${matName} Tools§r`, `textures/tcs/cwp/ui/upg_icons/double/${material}/double_${material}_sword`)
	form.button(`§l${colorMap[material]}Triple ${matName} Tools§r`, `textures/tcs/cwp/ui/upg_icons/triple/${material}/triple_${material}_sword`)
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");

	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === 2) {
			showUpgradedToolsMaterials(player);
		} else {
			const type = response.selection === 0 ? "double" : "triple";
			showUpgradedToolsItems(player, material, type);
		}
	});
}

async function showUpgradedToolsItems(player, material, type = "double") {
	const typeName = type.charAt(0).toUpperCase() + type.slice(1);
	const form = new ActionFormData().title(`${colorMap[material]}§l${typeName} ${main_menu.materialNames[material]} Tools§r`)
	upgradedTools.forEach((tool) => {
		const toolName = tool.charAt(0).toUpperCase() + tool.slice(1);
		form.button(`${colorMap[material]}§l${typeName} ${main_menu.materialNames[material]} ${toolName}§r`, `textures/tcs/cwp/ui/upg_icons/${type}/${material}/${type}_${material}_${tool}`)
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === upgradedTools.length) {
			showUpgradedToolsTypeSelection(player, material);
		} else {
			const tool = upgradedTools[response.selection];
			showUpgradedToolDetail(player, material, tool, type);
		}
	});
}

async function showUpgradedToolDetail(player, material, tool, type = "double") {
	const data = getUpgradedToolData(type, material, tool);
	if (!data) {
		showUpgradedToolsItems(player, material, type);
		return;
	}
	const form = new ActionFormData()
		.title(`§l${colorMap[material]}${data.result}§r`)
		.body(
			`Upgrade ${data.input1} to a ${data.result}!\n\n` +
				`§9Combine these items:§r\n` +
				`1x ${data.input1}\n` +
				`${data.input2}\n`
		)
		.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		showUpgradedToolsItems(player, material, type);
	});
}

export async function onItemUse(event) {
	const player = event.source;
	showWelcomePage(player);
	player.playSound("tcs_cwp:book_open");
}


async function showWelcomePage(player) {
	const form = new ActionFormData()
		.title("§l§1Combine Weapons Guide Book§r")
		.body("")
		.button("§l§9Special Weapons§r", "textures/tcs/cwp/ui/categories/special_items")
		.button("§l§uSword Sets§r", "textures/tcs/cwp/ui/categories/sword_sets")
		.button("§l§9Armor Sets§r", "textures/tcs/cwp/ui/categories/armor_sets")
		.button("§l§2Fused Weapons & Tools§r", "textures/tcs/cwp/ui/categories/fused_weapons_and_tools")
		.button("§l§6Double and Triple\nWeapons & Tools   §r", "textures/tcs/cwp/ui/categories/upgraded_weapons_and_tools")
		.button("§l§sAbout§r", "textures/tcs/cwp/ui/info");

	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		switch (response.selection) {
			case 0:
				showSpecialItemsList(player, "§l§9Special Weapons§r");
				break;
			case 1:
				showSwordSetMaterials(player, "§l§uSword Sets§r");
				break;
			case 2:
				showArmorTypes(player, "§l§bArmor Sets§r");
				break;
			case 3:
				showFusedToolsMaterials(player, "§l§2Fused Weapon & Tools§r");
				break;
			case 4:
				showUpgradedToolsMaterials(player);
				break;
			case 5:
				showAboutPage(player);
				break;
		}
	});
}


async function showSwordSetMaterials(player) {
	const form = new ActionFormData().title("§l§uSword Sets§r");
	swordSetMaterials.forEach((mat) => {
		const matName =
			main_menu.materialNames[mat] ||
			mat?.charAt(0).toUpperCase() + mat?.slice(1) ||
			"";
		const textureMat = mat === "wood" ? "wooden" : mat;
		const iconPath = `textures/tcs/cwp/ui/sword_set_icons/${textureMat}/poisonous_${textureMat}_sword`;
		const color = colorMap[mat] ?? "";
		form.button(`§l${color}${matName} Swords§r`, iconPath);
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === swordSetMaterials.length) {
			showWelcomePage(player);
		} else {
			const mat = swordSetMaterials[response.selection];
			showSwordSetList(player, mat);
		}
	});
}

async function showSwordSetList(player, material) {
	const matName =
		main_menu.materialNames[material] ||
		material?.charAt(0).toUpperCase() + material?.slice(1) ||
		"";
	const color = colorMap[material] ?? "";
	const form = new ActionFormData().title(`${color}§l${matName} Sword Set§r`);
	swordSetSwords.forEach((s) => {
		const textureMat = material === "wood" ? "wooden" : material;
		const iconPath = `textures/tcs/cwp/ui/sword_set_icons/${textureMat}/${s.iconSuffix}_${textureMat}_sword`;
		const color = colorMap[material] ?? "";
		form.button(`§l${color}${s.name} ${matName} Sword§r`, iconPath);
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === swordSetSwords.length) {
			showSwordSetMaterials(player);
		} else {
			const sword = swordSetSwords[response.selection];
			showSwordSetDetail(player, material, sword);
		}
	});
}

async function showSwordSetDetail(player, material, sword) {
	const matName =
		main_menu.materialNames[material] ||
		material?.charAt(0).toUpperCase() + material?.slice(1) ||
		"";
	const color = colorMap[material] ?? "";
	const title = `§l${color}${sword.name} ${matName} Sword§r`;
	const body =
		`${sword.effect}\n\n` +
		`§9Combine these items:§r\n` +
		`1x ${matName} Sword\n` +
		`1x ${sword.ingredient}\n`;
	const form = new ActionFormData()
		.title(title)
		.body(body)
		.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		showSwordSetList(player, material);
	});
}

async function showSpecialItemsList(player) {
	const form = new ActionFormData()
		.title("§l§9Special Items§r")
		.body("Choose a special item to learn more about it:");

	specialItems.forEach((item) => {
		form.button(`§l§${item.color}${item.name}§r`, item.icon);
	});

	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");

	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === specialItems.length) {
			showWelcomePage(player);
		} else {
			const item = specialItems[response.selection];
			showSpecialItemDetail(player, item);
		}
	});
}

async function showSpecialItemDetail(player, item) {
	const form = new ActionFormData()
		.title(`§l§${item.color}${item.name}§r`)
		.body(
			`${item.description}\n\n` +
				`§9Combine these items:§r\n` +
				`1x ${item.baseItem}\n` +
				`1x ${item.component}`
		)
		.button("§l§qBack§r", "textures/tcs/cwp/ui/back");

	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		showSpecialItemsList(player);
	});
}

async function showFusedToolsMaterials(player) {
	const form = new ActionFormData().title("§l§2Fused Weapons & Tools§r");
	main_menu.fused_tools.forEach((mat) => {
		let iconPath;
		if (mat.id === "back") {
			iconPath = `textures/tcs/cwp/${mat.iconSuffix}`;
		} else {
			iconPath = `textures/tcs/cwp/ui/fused_tools_icons/${mat.id}/${mat.iconSuffix}`;
		}
		form.button(`§l§${mat.color}${mat.name}§r`, iconPath);
	});
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		const selected = main_menu.fused_tools[response.selection];
		if (!selected) {
			return;
		}
		if (selected.id === "back") {
			showWelcomePage(player);
			return;
		}
		showFusedMaterialInfo(player, selected.id);
	});
}

async function showFusedMaterialInfo(player, materialId) {
	if (materialId === "back") {
		showFusionCategories(player);
		return;
	}
	const matName = main_menu.materialNames[materialId] || materialId;
	const form = new ActionFormData().title(
		`§l${colorMap[materialId]}Fused Tools & Weapons§r`
	);
	main_menu.fusedCombinations.forEach((comb) => {
		const iconPath = `textures/tcs/cwp/ui/fused_tools_icons/${materialId}/${materialId}_${comb.iconSuffix}`;
		const color = colorMap[materialId] || "§f";
		form.button(`§l${color}${matName} ${comb.result}§r`, iconPath);
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === main_menu.fusedCombinations.length) {
			showFusedToolsMaterials(player);
		} else {
			const comb = main_menu.fusedCombinations[response.selection];
			showFusedCombinationDetail(player, materialId, comb.id);
		}
	});
}

async function showFusedCombinationDetail(player, materialId, combinationId) {
	const matName = main_menu.materialNames[materialId] || materialId;
	const comb = main_menu.fusedCombinations.find((c) => c.id === combinationId);
	if (!comb) {
		showFusedMaterialInfo(player, materialId);
		return;
	}
	const matColor = colorMap[materialId] || "§f";
	const resultName = `${matColor}§l${matName} ${comb.result}§r`;
	const [first, second] = comb.name.split(" + ");
	const input1 = `${matName} ${first}`;
	const input2 = `${matName} ${second}`;
	const input3 = `1x ${matName} ${first}`;
	const input4 = `1x ${matName} ${second}`;
	const fuseText = "§9Combine these items:§r";
	const form = new ActionFormData()
		.title(resultName)
		.body(
			`Combine ${input1} and ${input2} into one extra useful tool!\n\n` +
				`${fuseText}\n` +
				`${input3}\n` +
				`${input4}\n\n`
		)
		.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		showFusedMaterialInfo(player, materialId);
	});
}

async function showAboutPage(player) {
	const form = new ActionFormData()
		.title("§lAbout Combine Weapons§r")
		.body(
			"§6§lCombine Weapons Add-On§r lets you craft powerful new gear!\n\n" +
			"§9§lPowerful weapons§r, §l§aunique tools§r, §l§6upgraded armor sets§r and much more. All designed to enhance and expand your survival adventure.\n\n" +
			"Experiment with 200+ fusion recipes, discover new combat strategies and exploration techniques.\n\n" +
			"Browse the §9§lCombine Weapons Guide Book§r to find all available recipes and start fusing today!\n\n" +
			"Don't forget to give §6§lCombine Weapons Add-On§r a §l§e5-STAR§r rating\non the Marketplace!\n "
		)
		.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		showWelcomePage(player);
	});
}

async function showArmorTypes(player) {
	const form = new ActionFormData()
		.title("§lArmor Sets§r")
		.body(" ");
	armorTypes.forEach((type) => {
		form.button(`§l§${type.color}${type.name} Armor§r`, type.icon);
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === armorTypes.length) {
			showWelcomePage(player);
		} else {
			const type = armorTypes[response.selection].id;
			showArmorParts(player, type);
		}
	});
}

async function showArmorParts(player, armorType) {
	const typeObj = armorTypes.find((t) => t.id === armorType);
	const matColor = typeObj.color;
	const typeName = typeObj.name;
	const fullSetBonus = typeObj.fullSetBonus;
	
	const form = new ActionFormData()
		.title(`§l§${matColor}${typeName} Armor§r`)
		.body(`${fullSetBonus}`);
	armorParts.forEach((part) => {
		const iconPath = `textures/tcs/cwp/ui/armor_set_icons/${armorType}_${part.id}_icon`;
		form.button(`§l§${matColor}${typeName} ${part.name}§r`, iconPath);
	});
	form.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		if (response.selection === armorParts.length) {
			showArmorTypes(player);
		} else {
			const part = armorParts[response.selection].id;
			showArmorDetail(player, armorType, part);
		}
	});
}

async function showArmorDetail(player, armorType, part) {
	const typeObj = armorTypes.find((t) => t.id === armorType);
	const matColor = typeObj.color;
	const typeName = typeObj.name;
	const partName = armorParts.find((p) => p.id === part).name;
	const partDesc = armorParts.find((p) => p.id === part).partDesc;
	const recipe = typeObj.recipe;
	const description = armorDescriptions[armorType]?.[part] || `${typeName} ${partDesc}`;
	const form = new ActionFormData()
		.title(`§l§${matColor}${typeName} ${partName}§r`)
		.body(
			`${description}\n\n` +
			`§9Combine these items:§r\n` +
			`1x ${typeObj.material} ${partName}\n` +
			`1x ${recipe}\n`
		)
		.button("§l§qBack§r", "textures/tcs/cwp/ui/back");
	form.show(player).then((response) => {
		if (response.canceled) {
			return;
		}
		showArmorParts(player, armorType);
	});
}
