import {
  ActionRowBuilder,
  EmbedBuilder,
  ModalBuilder,
  PermissionFlagsBits,
  TextInputBuilder,
  TextInputStyle,
  type ButtonInteraction,
  type ModalSubmitInteraction,
  type TextChannel
} from 'discord.js';
import { t } from '@nexumi/shared';
import type { BotContext } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { POLL_BUTTON_PREFIX } from './poll.js';
import { handlePollVote } from './poll.js';
import { parseHexColor } from './service.js';

export { POLL_BUTTON_PREFIX, pollButtonId } from './poll.js';

export function isPollButton(customId: string): boolean {
  return customId.startsWith(POLL_BUTTON_PREFIX);
}

export async function handlePollButton(
  interaction: ButtonInteraction,
  context: BotContext
): Promise<void> {
  await handlePollVote(interaction, context);
}

export const EMBED_MODAL_ID = 'util:embed:modal';

export function isEmbedModal(customId: string): boolean {
  return customId === EMBED_MODAL_ID;
}

export async function showEmbedBuilderModal(interaction: {
  showModal: (modal: ModalBuilder) => Promise<unknown>;
}): Promise<void> {
  const modal = new ModalBuilder()
    .setCustomId(EMBED_MODAL_ID)
    .setTitle('Embed Builder')
    .addComponents(
      new ActionRowBuilder<TextInputBuilder>().addComponents(
        new TextInputBuilder()
          .setCustomId('title')
          .setLabel('Title')
          .setStyle(TextInputStyle.Short)
          .setRequired(false)
          .setMaxLength(256)
      ),
      new ActionRowBuilder<TextInputBuilder>().addComponents(
        new TextInputBuilder()
          .setCustomId('description')
          .setLabel('Description')
          .setStyle(TextInputStyle.Paragraph)
          .setRequired(true)
          .setMaxLength(4000)
      ),
      new ActionRowBuilder<TextInputBuilder>().addComponents(
        new TextInputBuilder()
          .setCustomId('color')
          .setLabel('Color (hex, e.g. 6366F1)')
          .setStyle(TextInputStyle.Short)
          .setRequired(false)
          .setMaxLength(7)
      )
    );

  await interaction.showModal(modal);
}

export async function handleEmbedModal(
  interaction: ModalSubmitInteraction,
  context: BotContext
): Promise<void> {
  const locale = await getGuildLocale(context.prisma, interaction.guildId);

  if (!interaction.inGuild() || !interaction.channelId) {
    await interaction.reply({ content: t(locale, 'generic.guildOnly'), ephemeral: true });
    return;
  }

  if (!interaction.memberPermissions?.has(PermissionFlagsBits.ManageMessages)) {
    await interaction.reply({ content: t(locale, 'generic.noPermission'), ephemeral: true });
    return;
  }

  const title = interaction.fields.getTextInputValue('title') || undefined;
  const description = interaction.fields.getTextInputValue('description');
  const colorInput = interaction.fields.getTextInputValue('color');
  const parsedColor = colorInput ? parseHexColor(colorInput) : 0x6366f1;

  if (colorInput && parsedColor === null) {
    await interaction.reply({ content: t(locale, 'utility.embed.invalidColor'), ephemeral: true });
    return;
  }

  const embed = new EmbedBuilder()
    .setDescription(description)
    .setColor(parsedColor ?? 0x6366f1);
  if (title) {
    embed.setTitle(title);
  }

  const channel = (await context.client.channels.fetch(interaction.channelId)) as TextChannel;
  await channel.send({ embeds: [embed] });

  await interaction.reply({ content: t(locale, 'utility.embed.sent'), ephemeral: true });
}
