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

const LANGUAGES = {
  'en': 'English',
  'es': 'Spanish',
  'fr': 'French',
  'de': 'German',
  'it': 'Italian',
  'pt': 'Portuguese',
  'ru': 'Russian',
  'ja': 'Japanese',
  'ko': 'Korean',
  'zh': 'Chinese',
  'ar': 'Arabic',
  'hi': 'Hindi',
  'nl': 'Dutch',
  'pl': 'Polish',
  'tr': 'Turkish',
  'vi': 'Vietnamese',
  'th': 'Thai',
  'sv': 'Swedish',
  'da': 'Danish',
  'fi': 'Finnish'
};

module.exports = {
  data: new SlashCommandBuilder()
    .setName('translate')
    .setDescription('Translate text to another language')
    .addStringOption(option =>
      option.setName('text')
        .setDescription('The text to translate')
        .setRequired(true)
        .setMaxLength(500)
    )
    .addStringOption(option =>
      option.setName('to')
        .setDescription('Target language')
        .setRequired(true)
        .addChoices(
          { name: 'English', value: 'en' },
          { name: 'Spanish', value: 'es' },
          { name: 'French', value: 'fr' },
          { name: 'German', value: 'de' },
          { name: 'Italian', value: 'it' },
          { name: 'Portuguese', value: 'pt' },
          { name: 'Russian', value: 'ru' },
          { name: 'Japanese', value: 'ja' },
          { name: 'Korean', value: 'ko' },
          { name: 'Chinese', value: 'zh' }
        )
    ),

  async execute(interaction, supabase, client) {
    const text = interaction.options.getString('text');
    const targetLang = interaction.options.getString('to');
    const mode = await getServerMode(supabase, interaction.guildId);

    await interaction.deferReply();

    try {
      const response = await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=auto|${targetLang}`);
      const data = await response.json();

      if (data.responseStatus !== 200 || !data.responseData?.translatedText) {
        throw new Error('Translation failed');
      }

      const translated = data.responseData.translatedText;
      const detectedLang = data.responseData.detectedLanguage || 'auto';

      const embed = new EmbedBuilder()
        .setColor(getEmbedColor(mode))
        .setTitle('🌐 Translation')
        .addFields(
          { name: '📥 Original', value: text.substring(0, 1000) },
          { name: `📤 ${LANGUAGES[targetLang] || targetLang}`, value: translated.substring(0, 1000) }
        )
        .setFooter({ text: `Translated to ${LANGUAGES[targetLang]}` })
        .setTimestamp();

      await interaction.editReply({ embeds: [embed] });
    } catch (e) {
      const embed = new EmbedBuilder()
        .setColor(EMBED_COLORS.error)
        .setTitle('🌐 Translation Error')
        .setDescription('Failed to translate text. Please try again.')
        .setTimestamp();
      await interaction.editReply({ embeds: [embed] });
    }
  },
};
