import { createCommand } from "@lib/utils";
import { SlashCommandBuilder, PermissionFlagsBits, ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder, ModalSubmitInteraction } from "discord.js";
import { config, saveConfig } from "@lib/config";
import type { GameConfigType } from "@lib/config";
import { createSuccessEmbed, createErrorEmbed } from "@lib/embeds";

export const configCommand = createCommand({
    data: new SlashCommandBuilder()
        .setName("config")
        .setDescription("Edit the bot configuration")
        .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
    execute: async (interaction) => {
        console.log(`Config command executed by ${interaction.user.tag}`);
        const replacer = (key: string, value: any) => {
            if (typeof value === 'bigint') {
                return value.toString();
            }
            return value;
        };

        const currentConfigJson = JSON.stringify(config, replacer, 4);

        const modal = new ModalBuilder()
            .setCustomId("config-modal")
            .setTitle("Edit Configuration");

        const jsonInput = new TextInputBuilder()
            .setCustomId("json-input")
            .setLabel("Configuration JSON")
            .setStyle(TextInputStyle.Paragraph)
            .setValue(currentConfigJson)
            .setRequired(true);

        const actionRow = new ActionRowBuilder<TextInputBuilder>().addComponents(jsonInput);
        modal.addComponents(actionRow);

        await interaction.showModal(modal);

        try {
            const submitted = await interaction.awaitModalSubmit({
                time: 300000, // 5 minutes
                filter: (i) => i.customId === "config-modal" && i.user.id === interaction.user.id
            });

            const jsonString = submitted.fields.getTextInputValue("json-input");

            try {
                const newConfig = JSON.parse(jsonString);
                saveConfig(newConfig as GameConfigType);

                await submitted.reply({
                    embeds: [createSuccessEmbed("Configuration updated successfully.", "Config Saved")]
                });
            } catch (parseError) {
                await submitted.reply({
                    embeds: [createErrorEmbed(`Invalid JSON: ${parseError instanceof Error ? parseError.message : String(parseError)}`, "Config Update Failed")],
                    ephemeral: true
                });
            }

        } catch (error) {
            // Timeout or other error handling if needed, usually just ignore timeouts for modals
            if (error instanceof Error && error.message.includes('time')) {
                // specific timeout handling if desired
            }
        }
    }
});
