const { SlashCommandBuilder, PermissionsBitField, ChannelType, ButtonStyle, ButtonBuilder, ActionRowBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ticket')
    .setDescription('Commands for managing a ticket')
    .addSubcommand(subcommand => subcommand
      .setName('create')
      .setDescription('Create a ticket with you and moderators'))
    .addSubcommand(subcommand => subcommand
      .setName('close')
      .setDescription('Close current ticket')),

  async execute({ interaction, createEmbed }) {
    if (interaction.options.getSubcommand() === 'create') {
      await interaction.reply({ embeds: [createEmbed.basic('Creating ticket channel...')], fetchReply: true, ephemeral: true });

      const ticketChannel = await interaction.member.guild.channels.create({
        name: `ticket-${interaction.user.username}`,
        type: ChannelType.GuildText,
        parent: process.env.TICKET_CATEGORY_ID,
        permissionOverwrites: [
          {
            id: interaction.guild.id,
            deny: [PermissionsBitField.Flags.ViewChannel],
          },
          {
            id: process.env.MODERATOR_ROLE_ID,
            allow: [PermissionsBitField.Flags.ViewChannel],
          },
          {
            id: interaction.user.id,
            allow: [PermissionsBitField.Flags.ViewChannel],
          },
        ],

      });

      await ticketChannel.send({ embeds: [createEmbed.basic(`${interaction.user} created a ticket`)] });

      interaction.editReply({ embeds: [createEmbed.basic(`${ticketChannel} has been created`)], emphemeral: true });

    } else if (interaction.options.getSubcommand() === 'close') {

      if (!interaction.channel.name.startsWith('ticket')) return interaction.reply({ embeds: [createEmbed.basic('You must execute this command inside a ticket channel')], emphemeral: true });

      const cancelRow = new ActionRowBuilder()
        .addComponents(
          new ButtonBuilder()
            .setCustomId('cancel')
            .setLabel('Cancel')
            .setStyle(ButtonStyle.Danger),
        );

      const closeMessage = await interaction.reply({ embeds: [createEmbed.basic('Closing ticket in 10 seconds...')], components: [cancelRow] });
      const collector = closeMessage.createMessageComponentCollector();

      const timeout = setTimeout(() => {
        try {
          interaction.channel.delete();
        } catch {}
      }, 10000);

      collector.on('collect', async () => {
        clearTimeout(timeout);
        await closeMessage.edit({ embeds: [createEmbed.basic('Ticket closing has been stopped')], components: [] });
      });
    }
  },
};
