import { 
  SlashCommandBuilder, 
  ChatInputCommandInteraction, 
  PermissionFlagsBits, 
  EmbedBuilder, 
  Colors, 
  ActionRowBuilder, 
  ButtonBuilder, 
  ButtonStyle,
  RoleSelectMenuBuilder,
  ComponentType
} from 'discord.js';
import { Command, CommandTrait } from '../core/command';
import { autoRoleService } from '../services/AutoRoleService';
import { t, SupportedLocale } from '../i18n';

class AutoRoleCommand extends Command {
  protected override readonly trait = CommandTrait.General;
  protected override guildOnly = true;

  protected override define() {
    return new SlashCommandBuilder()
      .setName('autorole')
      .setDescription('Configure automatic role assignment upon joining.')
      .setDescriptionLocalizations({
        ko: '입장 시 역할을 자동으로 부여하는 기능을 설정합니다.',
      })
      .setDefaultMemberPermissions(PermissionFlagsBits.Administrator);
  }

  protected override async handle(interaction: ChatInputCommandInteraction, locale: SupportedLocale) {
    const guild = interaction.guild!;
    const dashboard = await generateAutoRoleDashboard(guild, locale);
    await interaction.editReply({
      ...dashboard
    });
  }
}

export async function generateAutoRoleDashboard(guild: import('discord.js').Guild, locale: SupportedLocale) {
  const config = await autoRoleService.getConfig(guild.id);

  const embed = new EmbedBuilder()
    .setTitle(t(locale, 'commands.autorole.statusTitle'))
    .setColor(Colors.Blue)
    .setDescription(t(locale, 'commands.autorole.description') || '유저 및 봇이 서버에 접속할 때 자동으로 부여할 기본 역할을 선택하세요. 역할을 선택하면 즉시 활성화됩니다.');

  const userSelect = new RoleSelectMenuBuilder()
    .setCustomId('autorole_select_user')
    .setPlaceholder(t(locale, 'commands.autorole.userRolePlaceholder'))
    .setMaxValues(10);
  if (config?.userRoleIds && config.userRoleIds.length > 0) {
    userSelect.addDefaultRoles(config.userRoleIds);
  }

  const rowUserRole = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(userSelect);

  const botSelect = new RoleSelectMenuBuilder()
    .setCustomId('autorole_select_bot')
    .setPlaceholder(t(locale, 'commands.autorole.botRolePlaceholder'))
    .setMaxValues(10);
  if (config?.botRoleIds && config.botRoleIds.length > 0) {
    botSelect.addDefaultRoles(config.botRoleIds);
  }

  const rowBotRole = new ActionRowBuilder<RoleSelectMenuBuilder>().addComponents(botSelect);

  return {
    embeds: [embed],
    components: [rowUserRole, rowBotRole]
  };
}

export default new AutoRoleCommand().toModule();
