import {
  SlashCommandSubcommandBuilder,
  EmbedBuilder,
  type ChatInputCommandInteraction,
} from 'discord.js';
import { api } from '../api-client.js';
import { COLORS, PRIORITY_CONFIG, type Priority } from '../config.js';
import { logger } from '../logger.js';

export const data = new SlashCommandSubcommandBuilder()
  .setName('blockers')
  .setDescription('Show what\'s stuck and why')
  .addStringOption((opt) =>
    opt
      .setName('pipeline_id')
      .setDescription('Filter to a specific pipeline')
      .setRequired(false),
  );

export async function execute(interaction: ChatInputCommandInteraction): Promise<void> {
  await interaction.deferReply();

  const pipelineId = interaction.options.getString('pipeline_id') ?? undefined;

  try {
    const blockers = await api.getBlockers(pipelineId);

    if (blockers.length === 0) {
      const embed = new EmbedBuilder()
        .setTitle('✅ No Blockers')
        .setDescription('All pipelines are flowing smoothly. Nothing is stuck!')
        .setColor(COLORS.success)
        .setTimestamp();
      await interaction.editReply({ embeds: [embed] });
      return;
    }

    const embed = new EmbedBuilder()
      .setTitle(`🚧 Blockers (${blockers.length})`)
      .setDescription('Items that are stuck and need attention:')
      .setColor(COLORS.warning)
      .setTimestamp();

    for (const blocker of blockers.slice(0, 10)) {
      const priority = blocker.priority as Priority;
      const pConfig = PRIORITY_CONFIG[priority];
      const hoursStr = blocker.hoursBlocked < 1
        ? `${Math.round(blocker.hoursBlocked * 60)}m`
        : `${Math.round(blocker.hoursBlocked)}h`;

      let value = `**Reason:** ${blocker.blockReason}\n`;
      value += `**Pipeline:** ${blocker.pipelineName}\n`;
      value += `**Blocked for:** ${hoursStr}\n`;
      if (blocker.suggestedAction) {
        value += `**Suggested:** ${blocker.suggestedAction}`;
      }

      embed.addFields({
        name: `${pConfig.emoji} ${blocker.title}`,
        value,
      });
    }

    if (blockers.length > 10) {
      embed.setFooter({ text: `Showing 10 of ${blockers.length} blockers` });
    }

    await interaction.editReply({ embeds: [embed] });
  } catch (error) {
    logger.error('Failed to fetch blockers:', error);
    await interaction.editReply({
      content: `❌ Failed to fetch blockers: ${error instanceof Error ? error.message : 'Unknown error'}`,
    });
  }
}
