import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder } from "discord.js";
import { inventoryService } from "@/modules/inventory/inventory.service";
import { userService } from "@/modules/user/user.service";
import { createErrorEmbed } from "@lib/embeds";
import { getItemUseResultEmbed } from "@/modules/inventory/inventory.view";
import type { ItemUsageData } from "@/lib/types";
import { UserError } from "@/lib/errors";
import { config } from "@/lib/config";

export const use = createCommand({
    data: new SlashCommandBuilder()
        .setName("use")
        .setDescription("Use an item from your inventory")
        .addNumberOption(option =>
            option.setName("item")
                .setDescription("The item to use")
                .setRequired(true)
                .setAutocomplete(true)
        ),
    execute: async (interaction) => {
        await interaction.deferReply();

        const itemId = interaction.options.getNumber("item", true);
        const user = await userService.getOrCreateUser(interaction.user.id, interaction.user.username);
        if (!user) {
            await interaction.editReply({ embeds: [createErrorEmbed("Failed to load user data.")] });
            return;
        }

        try {
            const result = await inventoryService.useItem(user.id.toString(), itemId);

            const usageData = result.usageData;
            if (usageData) {
                for (const effect of usageData.effects) {
                    if (effect.type === 'TEMP_ROLE' || effect.type === 'COLOR_ROLE') {
                        try {
                            const member = await interaction.guild?.members.fetch(user.id.toString());
                            if (member) {
                                if (effect.type === 'TEMP_ROLE') {
                                    await member.roles.add(effect.roleId);
                                } else if (effect.type === 'COLOR_ROLE') {
                                    // Remove existing color roles
                                    const rolesToRemove = config.colorRoles.filter(r => member.roles.cache.has(r));
                                    if (rolesToRemove.length > 0) await member.roles.remove(rolesToRemove);
                                    await member.roles.add(effect.roleId);
                                }
                            }
                        } catch (e) {
                            console.error("Failed to assign role in /use command:", e);
                            result.results.push("⚠️ Failed to assign role (Check bot permissions)");
                        }
                    }
                }
            }

            const embed = getItemUseResultEmbed(result.results, result.item);

            await interaction.editReply({ embeds: [embed] });

        } catch (error: any) {
            if (error instanceof UserError) {
                await interaction.editReply({ embeds: [createErrorEmbed(error.message)] });
            } else {
                console.error("Error using item:", error);
                await interaction.editReply({ embeds: [createErrorEmbed("An unexpected error occurred while using the item.")] });
            }
        }
    },
    autocomplete: async (interaction) => {
        const focusedValue = interaction.options.getFocused();
        const userId = interaction.user.id;

        const results = await inventoryService.getAutocompleteItems(userId, focusedValue);

        await interaction.respond(results);
    }
});
