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('casier')
        .setDescription('Voir toutes les sanctions d\'un membre.')
        .addUserOption(option =>
            option.setName('membre')
                .setDescription('Le membre dont tu veux voir le casier')
                .setRequired(true)),

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

        const member = interaction.options.getUser('membre');

        try {
            const [rows] = await db.query(
                'SELECT * FROM logs WHERE userId = ? AND guildId = ? ORDER BY timestamp DESC',
                [member.id, 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: `✅ ${member.tag} n'a 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()
                    .setAuthor({ name: member.displayName, iconURL: member.displayAvatarURL({ dynamic: true }) })
                    .setTitle(`📋 Casier Judiciaire - Page ${pageIndex + 1}/${pages.length}`)
                    .setColor(colors.warning)
                    .setThumbnail(member.displayAvatarURL({ dynamic: true, size: 256 }))
                    .setDescription(`**${member.toString()}** • \`${member.tag}\``)
                    .setFooter({ text: `Total: ${sanctions.length} sanction(s) • ${interaction.guild.name}` })
                    .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);
                    const guildName = row.guildId
                        ? interaction.client.guilds.cache.get(row.guildId)?.name || 'Serveur inconnu'
                        : 'Serveur inconnu';
                    
                    const displayNumber = index + 1 + pageIndex * 10;

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

                return embed;
            });

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

            let currentPage = 0;
            const message = await interaction.editReply({ embeds: [embeds[currentPage]], components: pages.length > 1 ? [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 casier:', err);
            await interaction.editReply({ content: '❌ Une erreur est survenue lors de la récupération du casier.' });
        }
    },
};