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

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ticket')
    .setDescription('Create a ticket!')
    .addStringOption(option => option
      .setName('category')
      .setDescription('The category of the ticket')
      .setRequired(true)
      .addChoices(
        { name: 'Technical Problem', value: 'tech-problem' },
        { name: 'Griefing or Harm', value: 'grief-or-harm' },
        { name: 'Suggestion', value: 'suggestion' },
        { name: 'Other', value: 'other' },
      )),

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

    const category = interaction.options.getString('category');

    let ticketChannel;

    if (category === 'grief-or-harm') {
      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],
          },
        ],

      });
    } else if (category === 'tech-problem') {
      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.CONTRIBUTER_ROLE_ID,
            allow: [PermissionsBitField.Flags.ViewChannel],
          },
          {
            id: interaction.user.id,
            allow: [PermissionsBitField.Flags.ViewChannel],
          },
        ],
      });
    } else {
      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: interaction.user.id,
            allow: [PermissionsBitField.Flags.ViewChannel],
          },
        ],
      });
    }

    const closeRow = new ActionRowBuilder()
      .addComponents(
        new ButtonBuilder()
          .setCustomId('close')
          .setLabel('Close Ticket')
          .setStyle(ButtonStyle.Danger),
      );

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

    const ticketMessage = await ticketChannel.send({ embeds: [createEmbed.basic(`${interaction.user} created a ticket with the category **${category}**`)], components: [closeRow] });

    const collector = ticketMessage.createMessageComponentCollector();

    let ticketCancelMessage;
    let timeout;
    collector.on('collect', async i => {
      if (i.customId === 'close') {
        ticketCancelMessage = await ticketChannel.send({ embeds: [createEmbed.basic('Closing ticket in 10 seconds...')] });
        await ticketMessage.createMessageComponentCollector();
        await i.update({ components: [cancelRow] });
        timeout = setTimeout(() => ticketChannel.delete(), 10000);
      } else {
        clearTimeout(timeout);
        await ticketCancelMessage.edit({ embeds: [createEmbed.basic('Ticket closing has been stopped')] });
        await i.update({ components: [closeRow] });
      }
    });

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