import * as mc from '@minecraft/server';

import * as main from '../main';
import * as eventmanager from '../event_manager';

export const EVENTID = 5;

export const ITEM_LIST = [
	// --- Tag 0: Sammel-Zeug, Natur, Baugrundlage ---
	{
		id: "minecraft:oak_log",
		amount_min: 2,
		amount_max: 6,
		progress_required: 0,
		time: 80
	},
	{
		id: "minecraft:sand",
		amount_min: 4,
		amount_max: 6,
		progress_required: 0,
		time: 160
	},
	{
		id: "minecraft:stick",
		amount_min: 4,
		amount_max: 8,
		progress_required: 0,
		time: 80
	},
	{
		id: "minecraft:flower",
		amount_min: 2,
		amount_max: 4,
		progress_required: 0,
		time: 80
	},
	{
		id: "minecraft:cobblestone",
		amount_min: 6,
		amount_max: 12,
		progress_required: 0,
		time: 150
	},

	// --- Tag 1: Erste Nahrung & Rohstoffe ---
	{
		id: "minecraft:cobblestone",
		amount_min: 6,
		amount_max: 12,
		progress_required: 1,
		time: 80
	},
	{
		id: "minecraft:coal",
		amount_min: 2,
		amount_max: 5,
		progress_required: 1,
		time: 120
	},
	{
		id: "minecraft:torch",
		amount_min: 4,
		amount_max: 12,
		progress_required: 1,
		time: 60
	},

	// --- Tag 2: Eisenzeit beginnt ---
	{
		id: "minecraft:leather",
		amount_min: 2,
		amount_max: 6,
		progress_required: 2,
		time: 150
	},
	{
		id: "minecraft:wheat",
		amount_min: 3,
		amount_max: 8,
		progress_required: 2,
		time: 120
	},

	// --- Tag 3: Edelmetalle & Äpfel ---
	{
		id: "minecraft:gold_ingot",
		amount_min: 2,
		amount_max: 4,
		progress_required: 3,
		time: 300
	},
	{
		id: "minecraft:redstone",
		amount_min: 5,
		amount_max: 15,
		progress_required: 3,
		time: 150
	},

	// --- Tag 5: Diamanten & seltene Materialien ---
	{
		id: "minecraft:diamond",
		amount_min: 2,
		amount_max: 3,
		progress_required: 5,
		time: 480
	},
	{
		id: "minecraft:glowstone_dust",
		amount_min: 4,
		amount_max: 10,
		progress_required: 5,
		time: 180
	},
	{
		id: "minecraft:potion",
		amount_min: 1,
		amount_max: 1,
		progress_required: 5,
		time: 200
	},

	// --- Tag 7: Emeralds, Netherite, "Prestige" ---
	{
		id: "minecraft:emerald",
		amount_min: 1,
		amount_max: 1,
		progress_required: 7,
		time: 600
	},
	{
		id: "minecraft:netherite_ingot",
		amount_min: 1,
		amount_max: 1,
		progress_required: 7,
		time: 900
	},

	// --- Tag 10: Fun / Endgame Items ---
	{
		id: "minecraft:music_disc",
		amount_min: 1,
		amount_max: 1,
		progress_required: 10,
		time: 300
	},
	{
		id: "minecraft:heart_of_the_sea",
		amount_min: 1,
		amount_max: 1,
		progress_required: 10,
		time: 360
	}
];

export const ITEM_LIST_CREEPY = [
	// --- Tag 0: Sammel-Zeug, Natur, Baugrundlage ---
	{
		id: "minecraft:command_block",
		amount_min: 1,
		amount_max: 1,
		progress_required: 0,
		time: 60
	},
	{
		id: "minecraft:dragon_egg",
		amount_min: 1,
		amount_max: 1,
		progress_required: 0,
		time: 60
	},
	{
		id: "minecraft:heart",
		amount_min: 1,
		amount_max: 1,
		progress_required: 0,
		time: 30
	},
	{
		id: "minecraft:tnt",
		amount_min: 1,
		amount_max: 1,
		progress_required: 0,
		time: 60
	}
]

const ITEM_EVENT_REWARDS = [
	{ id: "minecraft:iron_pickaxe", amount: 1, xp: 4 },
	{ id: "minecraft:diamond", amount: 1, xp: 4 },
	{ id: "minecraft:diamond", amount: 2, xp: 4 },
	{ id: "minecraft:gold_ingot", amount: 3, xp: 4 },
	{ id: "minecraft:sugar", amount: 1, xp: 4 },
	{ id: "minecraft:sugar", amount: 2, xp: 4 },
	{ id: "minecraft:egg", amount: 2, xp: 4 },
	{ id: "minecraft:egg", amount: 3, xp: 4 },
	{ id: "minecraft:wheat", amount: 3, xp: 4 },
	{ id: "minecraft:wheat", amount: 5, xp: 4 },
	{ id: "minecraft:milk_bucket", amount: 2, xp: 4 },
	{ id: "minecraft:milk_bucket", amount: 3, xp: 4 },
	{ id: "minecraft:cake", amount: 1, xp: 4 },
	{ id: "minecraft:cake", amount: 1, xp: 4 },
	{ id: null, amount: 0, xp: 9 },
	{ id: null, amount: 0, xp: 5 },
	{ id: null, amount: 0, xp: 5 }
];


export default class ItemEvent {

	eventID;
	name = "Item Event";
	description = "text.blocklab_friend_exe:emoticon.item";
	giveitemText = "text.blocklab_friend_exe:item_give";
	wrongitemText = "text.blocklab_friend_exe:item_wrong";
	progress = "";
	itemName = "blocklab_friend_exe:item.oak_planks.singular";
	item_amount = "2";
	time = 60;
	texture = "";
	isActive = true;
	complete = false;
	dayEvent = false;

	itemsNeeded = 0;
	itemID = "";
	maxItems = 0;

	completeText = "text.blocklab_friend_exe:emoticon.item_complete";
	failed = "text.blocklab_friend_exe:emoticon.item_failed";


	constructor() {
		this.eventID = EVENTID;
	}

	activate(friend_exe) {
		const day = mc.world.getDay();
		const randomItem = this.getRandomItemForDay(day);
		this.itemID = randomItem.id;
		this.itemName = `${randomItem.id.replace("minecraft:", "blocklab_friend_exe:item.")}`;
		this.itemsNeeded = main.randInt(randomItem.amount_min, randomItem.amount_max);
		this.maxItems = this.itemsNeeded;

		this.progress = `${this.maxItems - this.itemsNeeded}/${this.maxItems}`
		mc.world.sendMessage({
			rawtext: [
				{
					translate: `text.blocklab_friend_exe:event.item.${main.randInt(0, 7)}`, with: { rawtext: [{ text: String(this.maxItems) }, { translate: this.itemName }] }
				},
				{ text: " §c(" },
				{ text: this.progress },
				{ text: "§c)" }
			]
		});
	}

	tick(friend_exe, mood, moodStage) {
		this.time--;
		if (this.time == 60 || this.time == 30 || this.time == 15 || this.time == 5) {
			main.playTimeclockSound();
		}
		if (this.time == 60) {
			mc.world.sendMessage({
				rawtext: [
					{ translate: `text.blocklab_friend_exe:emoticon.timer.${main.randInt(0, 2)}` }]
			});
		}
		if (this.time == 3 || this.time == 2 || this.time == 1) {
			friend_exe.runCommand(`execute as @a at @s run playsound note.bit @s ~ ~ ~ 1 1.5`);
			mc.world.sendMessage(`§c${this.time}...`);
		}
		if (this.itemsNeeded <= 0) {
			if (this.itemsNeeded <= 0) {
				main.setMood(friend_exe, mood + 30);
				//friend_exe.runCommand("playsound mob.ai-friend.friend_exe_party_troete @a ~ ~1 ~");
				main.PlayEmoteSound("happy");
				mc.system.runTimeout(() => {
					friend_exe.runCommand("replaceitem entity @s slot.weapon.mainhand 1 air");
					main.rewardPlayer(ITEM_EVENT_REWARDS);
				}, 60);

				// Progression logic
				const levelObjective = mc.world.scoreboard.getObjective(main.SCOREBOARD_ITEM_LEVEL);
				const progressObjective = mc.world.scoreboard.getObjective(main.SCOREBOARD_ITEM_PROGRESS);

				if (levelObjective && progressObjective) {
					const level = levelObjective.getScore(main.PARTICIPANT_NAME) ?? 0;
					const progress = progressObjective.getScore(main.PARTICIPANT_NAME) ?? 0;
					if (level < 3 || (level === 3 && progress < 10)) {
						if (progress < 10) {
							progressObjective.setScore(main.PARTICIPANT_NAME, progress + 1);
						} else if (level < 3) {
							progressObjective.setScore(main.PARTICIPANT_NAME, 0);
							levelObjective.setScore(main.PARTICIPANT_NAME, level + 1);
						}
					}
				}
				if (this.maxItems == 1) {
					mc.world.sendMessage({
						rawtext: [{ translate: `text.blocklab_friend_exe:item_complete.${main.randInt(0, 7)}` }]
					});
				} else {
					mc.world.sendMessage({
						rawtext: [{ translate: `text.blocklab_friend_exe:item_complete.more.${main.randInt(0, 7)}` }]
					});
				}
				this.complete = true;
				this.isActive = false;
			}
		} else if (this.time == 0) {
			friend_exe.runCommand("replaceitem entity @s slot.weapon.mainhand 1 air");
			main.setMood(friend_exe, mood - (main.isFirstDay() ? (this.dayEvent ? 20 : 30) : (this.dayEvent ? 15 : 20)));
			main.feedBackSound();
			mc.world.sendMessage({
				rawtext: [
					{ translate: this.failed }]
			});
			main.PlayEmoteSound("okay");
			this.isActive = false;
		}
	}

	giveItem(player, friend_exe, item) {
		if (this.itemsNeeded == 0) return false;

		let isMatchingItem = item.typeId === this.itemID
			|| (this.itemID == "minecraft:flower" && (item.typeId.includes("peony") || item.typeId.includes("allium") || item.typeId.includes("dandelion") || item.typeId.includes("poppy") || item.typeId.includes("orchid") || item.typeId.includes("rose") || item.typeId.includes("tulip") || item.typeId.includes("flower")))
			|| this.itemID.includes("_planks") && item.typeId.includes("_planks")
			|| this.itemID.includes("log") && item.typeId.includes("log")
			|| this.itemID.includes("music_disc") && item.typeId.includes("music_disc");
		if (!isMatchingItem) {
			if (this.dayEvent) {
				player.sendMessage({
					rawtext: [
						{
							translate: this.wrongitemText, with: { rawtext: [{ text: String(this.itemsNeeded) }, { translate: this.itemName }] }
						}
					]
				});
				player.runCommand(`playsound mob.villager.no @s ~ ~ ~ 1 1.1`);
			} else {
				player.runCommand(`playsound mob.ai-friend.alarm_malfunction @s ~ ~ ~`);
			}
			return false;
		} else {
			friend_exe.runCommand(`replaceitem entity @s slot.weapon.mainhand 1 ${item.typeId}`);
			main.PlayEmote("stage0_happy.2", 2);
			//friend_exe.runCommand("playanimation @s animation.blocklab_friend_exe.stage0_happy.2");
			const item_amount = item.amount;
			main.removeItem(player, item, this.itemsNeeded);
			this.itemsNeeded = Math.max(0, this.itemsNeeded - item_amount);
			this.time += 60;
			this.progress = `${this.maxItems - this.itemsNeeded}/${this.maxItems}`


			mc.world.sendMessage({
				rawtext: [
					{
						translate: this.giveitemText, with: { rawtext: [{ text: String(player.name) }, { translate: this.itemName }] }
					},
					{ text: ". §c(" },
					{ text: this.progress },
					{ text: "§c)" }
				]
			});

			friend_exe.runCommand(`particle minecraft:heart_particle ~ ~2.2 ~`);
			return true;
		}
	}

	deactivate(friend_exe) {
		this.isActive = false;
	}

	getRandomItemForDay(day) {
		this.dayEvent = eventmanager.isGoodTime();
		const availableItems = this.dayEvent ? ITEM_LIST.filter(item => item.progress_required <= day) : ITEM_LIST_CREEPY;
		if (availableItems.length === 0) return null;

		const index = Math.floor(Math.random() * availableItems.length);
		return availableItems[index];
	}

	getRandomItem(level, progress, difficulty) {
		const filteredItems = ITEM_LIST.filter(item =>
			level == item.level_required &&
			difficulty <= item.difficulty &&
			progress >= (item.progress_required ?? 0)
		);

		if (filteredItems.length === 0) return null;

		const randomItem = filteredItems[Math.floor(Math.random() * filteredItems.length)];

		const amount = Math.floor(
			Math.random() * (randomItem.amount_max - randomItem.amount_min + 1)
		) + randomItem.amount_min;

		return {
			...randomItem,
			amount
		};
	}

}