const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, MessageFlags } = require('discord.js');
const db = require('../../functions/database/db.js');
const { colors } = require('../../utils/constants');

module.exports = {
    category: 'moderation',
    data: new SlashCommandBuilder()
        .setName('mysanctions')
        .setDescription('Voir tes propres sanctions sur ce serveur.'),
    async execute(interaction) {
        await interaction.deferReply({ flags: MessageFlags.Ephemeral });

        const userId = interaction.user.id;

        try {
            const [rows] = await db.query(
                'SELECT * FROM logs WHERE userId = ? AND guildId = ? ORDER BY timestamp DESC',
                [userId, interaction.guild.id]
            );

            const sanctions = rows.filter(row => 
                row.action !== 'Modification de sanction' && 
                row.action !== 'Révocation de sanction' &&
                row.action !== 'Modification de mute'
            );

            if (!sanctions.length) {
                return interaction.editReply({ content: '✅ Tu n\'as aucune sanction sur ce serveur.' });
            }

            const pages = [];
            for (let i = 0; i < sanctions.length; i += 10) {
                pages.push(sanctions.slice(i, i + 10));
            }

            const embeds = pages.map((page, pageIndex) => {
                const embed = new EmbedBuilder()
                    .setTitle(`📋 Mes Sanctions - Page ${pageIndex + 1}/${pages.length}`)
                    .setColor(colors.warning)
                    .setThumbnail(interaction.user.displayAvatarURL({ dynamic: true }))
                    .setFooter({ text: `Total: ${sanctions.length} sanction(s)` })
                    .setTimestamp();

                page.forEach((row, index) => {
                    const date = `<t:${Math.floor(row.timestamp / 1000)}:F>`;
                    const actionCapitalized = row.action.charAt(0).toUpperCase() + row.action.slice(1);

                    embed.addFields({
                        name: `#${index + 1 + pageIndex * 10} - ${actionCapitalized}`,
                        value: `**Modérateur:** <@${row.modId}> (${row.modTag || 'N/A'})\n` +
                            `**Raison:** ${row.reason || 'N/A'}\n` +
                            `**Date:** ${date}\n` +
                            `**Type:** ${row.type || 'N/A'}`,
                        inline: false
                    });
                });

                return embed;
            });

            if (pages.length === 1) {
                return interaction.editReply({ embeds: [embeds[0]] });
            }

            const row = new ActionRowBuilder().addComponents(
                new ButtonBuilder().setCustomId('prev').setLabel('⬅️ Précédent').setStyle(ButtonStyle.Primary),
                new ButtonBuilder().setCustomId('next').setLabel('Suivant ➡️').setStyle(ButtonStyle.Primary)
            );

            let currentPage = 0;
            const message = await interaction.editReply({ embeds: [embeds[currentPage]], components: [row] });

            const collector = message.createMessageComponentCollector({ time: 60_000 });
            collector.on('collect', async i => {
                if (i.user.id !== interaction.user.id) {
                    return i.reply({ content: '❌ Ce n\'est pas ton menu !', flags: MessageFlags.Ephemeral });
                }
                if (i.customId === 'next') {
                    currentPage = (currentPage + 1) % embeds.length;
                }
                if (i.customId === 'prev') {
                    currentPage = (currentPage - 1 + embeds.length) % embeds.length;
                }

                await i.update({ embeds: [embeds[currentPage]] });
            });

            collector.on('end', () => {
                message.edit({ components: [] }).catch(() => null);
            });

        } catch (err) {
            console.error('Erreur mysanctions:', err);
            await interaction.editReply({ content: '❌ Une erreur est survenue lors de la récupération de tes sanctions.' });
        }
    },
};