const { Client, GatewayIntentBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, REST, Routes, SlashCommandBuilder } = require('discord.js');
const axios = require('axios');
require('dotenv').config();

console.log('Starting bot...');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
    ]
});

console.log('Attempting to log in...');

client.once('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.login(process.env.BOT_TOKEN).then(() => {
    console.log('Login successful');
}).catch(error => {
    console.error('Login failed:', error);
});

// Remove the second login call
// client.login(process.env.BOT_TOKEN);

// Register Slash Commands
const commands = [
  new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Replies with Pong!'),
  new SlashCommandBuilder()
    .setName('finduser')
    .setDescription('Find a user by username')
    .addStringOption(option =>
      option.setName('username')
        .setDescription('The username to search for')
        .setRequired(true))
];

const rest = new REST({ version: '10' }).setToken(process.env.BOT_TOKEN);

(async () => {
  try {
    console.log('Started refreshing application (/) commands.');

    await rest.put(
      Routes.applicationCommands(client.user.id),
      { body: commands },
    );

    console.log('Successfully reloaded application (/) commands.');
  } catch (error) {
    console.error(error);
  }
})();

// Function to fetch user data
async function findUserByUsername(username) {
  try {
    const response = await axios.get(`https://www.vrbattles.gg/api/get_player_data_by_username/${username}`);
    return response.data;
  } catch (error) {
    console.error('Error fetching user data:', error);
    return null;
  }
}

// Function to get badge image URL
function getBadgeImageUrl(badgeName) {
  if (!badgeName) {
    return 'https://www.vrbattles.gg/assets/images/badges/xp_badges/A/BADGE_A1_72p.png';
  }

  badgeName = badgeName.toUpperCase().replace(/ /g, '_');
  let badgeUrl = 'https://www.vrbattles.gg/assets/images/badges/xp_badges/';

  if (badgeName.startsWith('A')) {
    badgeUrl += 'A/';
  } else if (badgeName.startsWith('B')) {
    badgeUrl += 'B/';
  } else if (badgeName.startsWith('C')) {
    badgeUrl += 'C/';
  } else {
    badgeUrl += 'A/';
  }

  badgeUrl += `BADGE_${badgeName}_72p.png`;
  console.log('Badge URL:', badgeUrl);
  return badgeUrl;
}

// Interaction handler
client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'ping') {
    await interaction.reply('Pong!');
  } else if (commandName === 'finduser') {
    const username = interaction.options.getString('username');
    
    await interaction.deferReply();

    const userData = await findUserByUsername(username);
    if (userData && userData.success) {
      let playerData;
      if (typeof userData.player_data === 'string') {
        try {
          playerData = JSON.parse(userData.player_data);
        } catch (error) {
          await interaction.editReply('Error parsing player data.');
          return;
        }
      } else {
        playerData = userData.player_data;
      }

      if (!playerData || !playerData.profile) {
        await interaction.editReply('User found but profile data is null. They need to log in to VRBattles to update their profile.');
        return;
      }

      const user = playerData.profile || {};
      const badgeImageUrl = getBadgeImageUrl(user.current_level_badge);

      const embed = new EmbedBuilder()
        .setTitle(`User: ${playerData.username || 'Unknown'}`)
        .setDescription(`Bio: ${user.bio || 'No bio available'}`)
        .addFields(
          { name: 'Country', value: user.country || 'Unknown', inline: true },
          { name: 'Rank', value: user.rank || 'Unranked', inline: true },
          { name: 'Level', value: user.level?.toString() || 'N/A', inline: true },
          { name: 'Prestige', value: user.prestige?.toString() || '0', inline: true },
          { name: 'Total XP', value: user.xp?.toString() || '0', inline: true }
        )
        .setImage(badgeImageUrl)
        .addFields({ name: 'XP Badge', value: ' ' })
        .setColor('#0099ff');

      if (user.avatar) {
        embed.setThumbnail(`https://www.vrbattles.gg/assets/uploads/profile/${user.avatar}`);
      }

      const row = new ActionRowBuilder()
        .addComponents(
          new ButtonBuilder()
            .setLabel('🔵 View Profile')
            .setStyle(ButtonStyle.Link)
            .setURL(`https://www.vrbattles.gg/profile/${playerData.username}`),
          new ButtonBuilder()
            .setLabel('🟡 Join Discord')
            .setStyle(ButtonStyle.Link)
            .setURL('https://discord.gg/j3DKVATPGQ') // Replace with your Discord invite URL
        );

      await interaction.editReply({ embeds: [embed], components: [row] });
    } else {
      await interaction.editReply('User not found or an error occurred while fetching data.');
    }
  }
});