const { Feedback, Configuration, UserPoints } = require('../database');
const { MessageActionRow, MessageSelectMenu, MessageEmbed, PermissionsBitField } = require('discord.js');
const { Modal, TextInputComponent, showModal } = require('discord-modals');
const cooldownSet = new Set();

async function getSupportRoles() {
  const roleTypes = ['مدير', 'قائد فريق', 'دعم التذاكر', 'دعم'];
  const supportRoles = {};
  for (const type of roleTypes) {
    const config = await Configuration.findOne({ where: { key: `${type}Role` } });
    supportRoles[`${type}Role`] = config ? config.value : null;
  }
  return supportRoles;
}

async function isUserBlacklisted(userId) {
  const blacklistConfig = await Configuration.findOne({ where: { key: `blacklist_${userId}` } });
  return blacklistConfig && blacklistConfig.value === 'true';
}

async function getRewardConfig() {
  try {
    const rewardReviewsConfig = await Configuration.findOne({ where: { key: 'rewardReviews' } });
    const rewardPointsConfig = await Configuration.findOne({ where: { key: 'rewardPoints' } });
    const rewardReviewsConsecutiveConfig = await Configuration.findOne({ where: { key: 'rewardReviewsConsecutive' } });

    return {
      rewardReviews: rewardReviewsConfig ? parseInt(rewardReviewsConfig.value, 10) : null,
      rewardPoints: rewardPointsConfig ? parseInt(rewardPointsConfig.value, 10) : null,
      rewardReviewsConsecutive: rewardReviewsConsecutiveConfig ? parseInt(rewardReviewsConsecutiveConfig.value, 10) : null,
    };
  } catch (error) {
    console.error('Error fetching reward configuration:', error); 
    return {}; 
  }
}

async function checkForRolePromotion(interaction, supportMemberId, newPoints) {
  const supportRoles = await getSupportRoles();
  const member = interaction.guild.members.cache.get(supportMemberId);
  if (!member) {
    return interaction.editReply({
      content: 'عضو الدعم غير موجود.',
      ephemeral: true,
    });
  }

  for (const roleType of ['Support', 'Ticket Support', 'Teamleader']) {
    const roleConfig = await Configuration.findOne({ where: { key: `${roleType}Role` } });
    const pointsConfig = await Configuration.findOne({ where: { key: `${roleType}Points` } });
    if (!roleConfig || !pointsConfig) continue;

    const roleId = roleConfig.value;
    const requiredPoints = parseInt(pointsConfig.value, 10);

    if (newPoints >= requiredPoints && !member.roles.cache.has(roleId)) {
      const roleToAssign = interaction.guild.roles.cache.get(roleId);
      if (roleToAssign) {
        await member.roles.add(roleToAssign);
        await member.send(`مبروك! لقد تمت ترقيتك إلى رتبة ${roleToAssign.name}.`);
      }
    }
  }
}

async function initializeDatabase() {
  db.query(`
    CREATE TABLE IF NOT EXISTS support_roles (
      id INT PRIMARY KEY AUTO_INCREMENT,
      role_id VARCHAR(255) UNIQUE,
      role_type VARCHAR(255) NOT NULL,
      points INT NOT NULL DEFAULT 0
    )
  `);
}

module.exports = {
  name: 'interactionCreate',
  async execute(interaction) {
    await initializeDatabase();
    const supportRoles = await getSupportRoles();
    const rewardConfig = await getRewardConfig(); // Fetch reward configuration

    if (interaction.isCommand()) {
        const command = interaction.client.commands.get(interaction.commandName);
        if (!command) return;

        try {
          await command.execute(interaction);
        } catch (error) {
          console.error(error);
          await interaction.reply({ content: 'حدث خطأ أثناء تنفيذ هذا الأمر!', ephemeral: true });
        }
    } else if (interaction.isButton() && interaction.customId === 'feedback_button') {
      if (await isUserBlacklisted(interaction.user.id)) {
        return interaction.reply({ content: 'غير مسموح لك بتقديم ملاحظات في هذا الوقت.', ephemeral: true });
      }
      if (cooldownSet.has(interaction.user.id)) {
        const rateLimitConfig = await Configuration.findOne({ where: { key: 'rateLimit' } });
        const rateLimitMinutes = rateLimitConfig ? parseInt(rateLimitConfig.value) : 15;
        return interaction.reply({ content: `لقد تجاوزت الحد المسموح به للتقييم. يرجى المحاولة مرة أخرى بعد ${rateLimitMinutes} دقيقة.`, ephemeral: true });
      }
      await interaction.guild.members.fetch();
      const supportMembers = interaction.guild.members.cache.filter(
        (member) => !member.user.bot && member.roles.cache.has(supportRoles.supportRole)
      );

      if (supportMembers.size === 0) {
        return interaction.reply({ content: 'لا يوجد أعضاء دعم متاحين.', ephemeral: true });
      }

      const targetUserId = interaction.message.mentions.users?.first()?.id;
      if (!targetUserId) {
        return interaction.reply({ content: 'يرجى ذكر المستخدم الذي تريد تقديم الملاحظات له.', ephemeral: true });
      }

      const supportMemberSelect = new MessageActionRow()
        .addComponents(
          new MessageSelectMenu()
            .setCustomId('support_member_select')
            .setPlaceholder('اختر عضو دعم')
            .addOptions(
              supportMembers.map((member) => ({
                label: member.user.username,
                value: member.id,
              }))
            )
        );

      // Send the selection menu as a hidden message
      await interaction.reply({
        content: 'اختر عضو دعم لتقديم الملاحظات:',
        components: [supportMemberSelect],
        ephemeral: true,
      });
    } else if (
      interaction.isSelectMenu() &&
      interaction.customId === "support_member_select"
    ) {
      const selectedSupportMemberId = interaction.values[0];

      const supportMember = interaction.guild.members.cache.get(
        selectedSupportMemberId
      );
      if (!supportMember)
        return interaction.followUp({
          content: "تم اختيار عضو دعم غير صحيح.",
          ephemeral: true,
        });

      const modal = new Modal()
        .setCustomId("feedback_modal")
        .setTitle(`قدم تقييمك ل ${supportMember.user.username}`);

      const ratingInput = new TextInputComponent()
        .setCustomId("rating")
        .setLabel("التقييم (من 0 إلى 5 نجوم)")
        .setStyle("SHORT") 
        .setPlaceholder("أدخل التقييم")
        .setRequired(true);

      const commentInput = new TextInputComponent()
        .setCustomId("comment")
        .setLabel("تعليق (اختياري)")
        .setStyle("LONG") 
        .setPlaceholder("أدخل تعليقك")
        .setRequired(false);

      modal.addComponents(ratingInput, commentInput);

      showModal(modal, {
        client: interaction.client,
        interaction: interaction,
      });
    } else if (interaction.customId === 'feedback_modal') {
      await interaction.deferReply({ ephemeral: true });

      const selectedSupportMemberId = interaction.message.content.split(' ')[4].replace('<@', '').replace('>', '');
      const rating = parseInt(interaction.fields.getTextInputValue('rating'));
      const comment = interaction.fields.getTextInputValue('comment');
      const userId = interaction.user.id; 

      try {
        // Validate rating (0-5 stars)
        if (rating < 0 || rating > 5 || isNaN(rating)) {
          return interaction.editReply({ content: 'Invalid rating. Please enter a number between 0 and 5.', ephemeral: true });
        }

        db.query(`INSERT INTO Feedbacks (userId, supportMemberId, rating, comment) VALUES (?, ?, ?, ?)`,
          [userId, selectedSupportMemberId, rating, comment],
          (err, rows) => {
            if (err) {
              console.error('Error inserting feedback:', err);
              return interaction.editReply({ content: 'An error occurred while saving the feedback.', ephemeral: true });
            }
            db.query(`SELECT value FROM Configurations WHERE key = 'feedbackChannel'`, async (err, rows) => {
                if (err) {
                  console.error('Error fetching feedback channel:', err);
                  return interaction.editReply({ content: 'An error occurred while fetching the feedback channel.', ephemeral: true });
                }
                const feedbackChannelId = rows.length > 0 ? rows[0].value : null;
                const feedbackChannel = interaction.guild.channels.cache.get(feedbackChannelId);
                if (!feedbackChannel) {
                  return interaction.editReply({ content: 'Feedback channel not found!', ephemeral: true });
                }

                db.query(
                  'INSERT INTO UserPoints (userId, points) VALUES (?, ?) ON DUPLICATE KEY UPDATE points = points + ?',
                  [selectedSupportMemberId, rating, rating],
                  (err) => {
                    if (err) {
                      console.error('Error updating user points:', err);
                      return;
                    }

                    db.query(`SELECT points FROM UserPoints WHERE userId = ?`, [selectedSupportMemberId], async (err, pointsRows) => {
                      if (err) {
                        console.error('Error fetching user points:', err);
                        return;
                      }

                      const newPoints = pointsRows.length > 0 ? pointsRows[0].points : 0;
                      await checkForRolePromotion(interaction, selectedSupportMemberId, newPoints);

                      db.query(`SELECT value FROM Configurations WHERE key = 'HRChannel'`, async (err, rows) => {
                        if (err) {
                          console.error('Error fetching HR channel:', err);
                          return interaction.editReply({ content: 'An error occurred while fetching the HR channel.', ephemeral: true });
                        }

                        const hrChannelId = rows.length > 0 ? rows[0].value : null;
                        const hrChannel = interaction.guild.channels.cache.get(hrChannelId);

                        if (!hrChannel) {
                          return interaction.editReply({ content: 'HR channel not found!', ephemeral: true });
                        }

                        const feedbackEmbed = new MessageEmbed()
                          .setTitle('New Feedback Received')
                          .setDescription(`**Support Member:** <@${selectedSupportMemberId}>
                                          **Rating:** ${rating}/5
                                          **Comment:** ${comment}`)
                          .setColor('#0099ff');

                        await hrChannel.send({ embeds: [feedbackEmbed] });

                        cooldownSet.add(userId);
                        const rateLimitConfig = await Configuration.findOne({ where: { key: 'rateLimit' } });
                        const rateLimitMinutes = rateLimitConfig ? parseInt(rateLimitConfig.value) : 15;
                        const rateLimitMs = rateLimitMinutes * 60 * 1000;
                        setTimeout(() => cooldownSet.delete(userId), rateLimitMs);
                        await interaction.editReply({ content: 'Thank you for your feedback!', components: [] });
                      }); 
                    }); 
                  }); 
              });
            }) catch (error) {
              console.error(error);
              await interaction.editReply({ content: 'An error occurred while saving feedback.', ephemeral: true});
            }
          }
  },
};