import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, PermissionFlagsBits, MessageFlags } from "discord.js";
import { createBaseEmbed } from "@lib/embeds";
import { configManager } from "@/lib/configManager";
import { config, reloadConfig } from "@/lib/config";
import { AuroraClient } from "@/lib/BotClient";

export const features = createCommand({
    data: new SlashCommandBuilder()
        .setName("features")
        .setDescription("Manage bot features and commands")
        .addSubcommand(sub =>
            sub.setName("list")
                .setDescription("List all commands and their status")
        )
        .addSubcommand(sub =>
            sub.setName("toggle")
                .setDescription("Enable or disable a command")
                .addStringOption(option =>
                    option.setName("command")
                        .setDescription("The name of the command")
                        .setRequired(true)
                )
                .addBooleanOption(option =>
                    option.setName("enabled")
                        .setDescription("Whether the command should be enabled")
                        .setRequired(true)
                )
        )
        .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
    execute: async (interaction) => {
        const subcommand = interaction.options.getSubcommand();

        if (subcommand === "list") {
            const activeCommands = AuroraClient.commands;
            const categories = new Map<string, string[]>();

            // Group active commands
            activeCommands.forEach(cmd => {
                const cat = cmd.category || 'Uncategorized';
                if (!categories.has(cat)) categories.set(cat, []);
                categories.get(cat)!.push(cmd.data.name);
            });

            // Config overrides
            const overrides = Object.entries(config.commands)
                .map(([name, enabled]) => `• **${name}**: ${enabled ? "✅ Enabled (Override)" : "❌ Disabled"}`);

            const embed = createBaseEmbed("Command Features", undefined, "Blue");

            // Add fields for each category
            const sortedCategories = [...categories.keys()].sort();
            for (const cat of sortedCategories) {
                const cmds = categories.get(cat)!.sort();
                const cmdList = cmds.map(name => {
                    const isOverride = config.commands[name] !== undefined;
                    return isOverride ? `**${name}** (See Overrides)` : `**${name}**`;
                }).join(", ");

                embed.addFields({ name: `📂 ${cat.toUpperCase()}`, value: cmdList || "None" });
            }

            if (overrides.length > 0) {
                embed.addFields({ name: "⚙️ Configuration Overrides", value: overrides.join("\n") });
            } else {
                embed.addFields({ name: "⚙️ Configuration Overrides", value: "No overrides set." });
            }

            // Check permissions manually as a fallback (though defaultMemberPermissions handles it at the API level)
            if (!interaction.memberPermissions?.has(PermissionFlagsBits.Administrator)) {
                await interaction.reply({ content: "❌ You need Administrator permissions to use this command.", flags: MessageFlags.Ephemeral });
                return;
            }

            await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
        } else if (subcommand === "toggle") {
            const commandName = interaction.options.getString("command", true);
            const enabled = interaction.options.getBoolean("enabled", true);

            await interaction.deferReply({ flags: MessageFlags.Ephemeral });

            configManager.toggleCommand(commandName, enabled);

            await interaction.editReply({ content: `✅ Command **${commandName}** has been ${enabled ? "enabled" : "disabled"}. Reloading configuration...` });

            // Reload config from disk (which was updated by configManager)
            reloadConfig();

            await AuroraClient.loadCommands(true);
            await AuroraClient.deployCommands();

            await interaction.editReply({ content: `✅ Command **${commandName}** has been ${enabled ? "enabled" : "disabled"}. Commands reloaded!` });
        }
    }
});
