import { 
  SlashCommandBuilder, 
  ChatInputCommandInteraction, 
  PermissionFlagsBits, 
  EmbedBuilder,
  Colors
} from 'discord.js';
import { prisma } from '../database';
import { t, SupportedLocale, SUPPORTED_LOCALES } from '../i18n';

export default {
  data: new SlashCommandBuilder()
    .setName('config')
    .setDescription('Configure bot features and server settings.')
    .setDescriptionLocalizations({
      ko: '봇의 기능 및 서버 설정을 관리합니다.',
    })
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    // --- System Subcommand ---
    .addSubcommand(subcommand =>
      subcommand
        .setName('system')
        .setDescription('Manage core system settings.')
        .setDescriptionLocalizations({ ko: '시스템 핵심 설정을 관리합니다.' })
        .addStringOption(option =>
          option.setName('action')
            .setDescription('System action to perform')
            .setRequired(true)
            .addChoices(
              { name: 'language (Server Locale)', value: 'language' },
            )
        )
        .addStringOption(option =>
          option.setName('locale')
            .setDescription('Language to use (for language action)')
            .addChoices(
              { name: 'English', value: 'en' },
              { name: '한국어', value: 'ko' },
            )
        )
    )
    // --- Features Subcommand ---
    .addSubcommand(subcommand =>
      subcommand
        .setName('features')
        .setDescription('Enable or disable specific bot features.')
        .setDescriptionLocalizations({
          ko: '봇의 특정 기능들을 활성화 또는 비활성화합니다.',
        })
        .addStringOption(option =>
          option.setName('target')
            .setDescription('Feature to configure')
            .setRequired(true)
            .addChoices(
              { name: 'mimic', value: 'mimic' },
              { name: 'emoji', value: 'emoji' },
            )
        )
        .addBooleanOption(option =>
          option.setName('enable')
            .setDescription('Whether to enable this feature')
            .setRequired(true)
        )
    ),

  async execute(interaction: ChatInputCommandInteraction, locale: SupportedLocale) {
    if (!interaction.guildId) return;
    const subcommand = interaction.options.getSubcommand();

    // --- SYSTEM ---
    if (subcommand === 'system') {
      const action = interaction.options.getString('action', true);

      // Removed 'setup' action (now in standalone /setup command)

      if (action === 'language') {
        const newLocale = interaction.options.getString('locale') as SupportedLocale;
        if (!newLocale) {
          return interaction.editReply({ 
            content: '❌ `locale` 옵션을 선택해주세요.', 
          });
        }
        
        if (!SUPPORTED_LOCALES.includes(newLocale)) {
          return interaction.editReply({ content: `Unsupported locale: ${newLocale}` });
        }

        await prisma.guildConfig.upsert({
          where: { guildId: interaction.guildId },
          update: { locale: newLocale },
          create: { guildId: interaction.guildId, locale: newLocale },
        });

        return interaction.editReply({
          content: t(newLocale, 'commands.language.serverSet', { locale: newLocale === 'ko' ? '한국어' : 'English' }),
        });
      }
    }

    // --- FEATURES ---
    if (subcommand === 'features') {
      const target = interaction.options.getString('target', true);
      const enable = interaction.options.getBoolean('enable', true);
      const updateData: any = {};
      
      let labelKey = '';
      if (target === 'mimic') {
        updateData.mimicEnabled = enable;
        labelKey = 'commands.config.mimic.label';
      } else if (target === 'emoji') {
        updateData.bigEmojiEnabled = enable;
        labelKey = 'commands.config.emoji.label';
      }

      await prisma.guildConfig.upsert({
        where: { guildId: interaction.guildId },
        update: updateData,
        create: {
          guildId: interaction.guildId,
          mimicEnabled: target === 'mimic' ? enable : false,
          bigEmojiEnabled: target === 'emoji' ? enable : false,
        },
      });

      const state = enable ? t(locale, 'commands.config.mimic.enabled') : t(locale, 'commands.config.mimic.disabled'); 
      const label = t(locale, labelKey);

      const embed = new EmbedBuilder()
        .setColor(enable ? Colors.Green : Colors.Grey)
        .setTitle(t(locale, 'commands.config.title'))
        .setDescription(`${label}: **${state}**`);

      return interaction.editReply({ embeds: [embed] });
    }
  },
};



