const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getServerMode, getEmbedColor } = require('../utils/modeHelper');

const afkUsers = new Map();

module.exports = {
  data: new SlashCommandBuilder()
    .setName('afk')
    .setDescription('Set your AFK status')
    .addStringOption(option =>
      option.setName('reason')
        .setDescription('Reason for being AFK')
        .setRequired(false)
        .setMaxLength(200)
    ),

  afkUsers,

  async execute(interaction, supabase, client) {
    const reason = interaction.options.getString('reason') || 'AFK';
    const userId = interaction.user.id;
    const guildId = interaction.guildId;
    
    const mode = await getServerMode(supabase, interaction.guildId);

    if (afkUsers.has(`${guildId}-${userId}`)) {
      afkUsers.delete(`${guildId}-${userId}`);
      
      const embed = new EmbedBuilder()
        .setColor(0x22C55E)
        .setTitle('👋 Welcome Back!')
        .setDescription('Your AFK status has been removed.')
        .setTimestamp();
      
      return interaction.reply({ embeds: [embed], ephemeral: true });
    }

    afkUsers.set(`${guildId}-${userId}`, {
      reason,
      timestamp: Date.now(),
      username: interaction.user.username
    });

    const embed = new EmbedBuilder()
      .setColor(getEmbedColor(mode))
      .setTitle('💤 AFK Status Set')
      .setDescription(`You are now AFK: **${reason}**`)
      .addFields({
        name: '💡 Tip',
        value: 'Use `/afk` again or send a message to remove your AFK status.'
      })
      .setTimestamp();

    await interaction.reply({ embeds: [embed] });
  },

  checkAfk(message) {
    const guildId = message.guildId;
    const userId = message.author.id;
    const key = `${guildId}-${userId}`;

    if (afkUsers.has(key)) {
      const afkData = afkUsers.get(key);
      afkUsers.delete(key);
      
      const duration = Math.floor((Date.now() - afkData.timestamp) / 1000);
      let timeStr;
      if (duration < 60) timeStr = `${duration} seconds`;
      else if (duration < 3600) timeStr = `${Math.floor(duration / 60)} minutes`;
      else timeStr = `${Math.floor(duration / 3600)} hours`;

      message.reply({
        content: `👋 Welcome back! You were AFK for ${timeStr}.`,
        allowedMentions: { repliedUser: false }
      }).catch(() => {});
    }

    const mentions = message.mentions.users;
    mentions.forEach(user => {
      const mentionKey = `${guildId}-${user.id}`;
      if (afkUsers.has(mentionKey)) {
        const afkData = afkUsers.get(mentionKey);
        const ago = Math.floor((Date.now() - afkData.timestamp) / 1000);
        let timeStr;
        if (ago < 60) timeStr = `${ago} seconds ago`;
        else if (ago < 3600) timeStr = `${Math.floor(ago / 60)} minutes ago`;
        else timeStr = `${Math.floor(ago / 3600)} hours ago`;

        message.reply({
          content: `💤 **${afkData.username}** is AFK: ${afkData.reason} (set ${timeStr})`,
          allowedMentions: { repliedUser: false }
        }).catch(() => {});
      }
    });
  }
};
