import {
  SlashCommandSubcommandBuilder,
  EmbedBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  type ChatInputCommandInteraction,
} from 'discord.js';
import { api } from '../api-client.js';
import { COLORS, PRIORITY_CONFIG, type Priority } from '../config.js';
import { buildBatchReviewEmbed, classifyRisk } from '../embeds/batch-review.js';
import { logger } from '../logger.js';

export const data = new SlashCommandSubcommandBuilder()
  .setName('queue')
  .setDescription('Show pending decision queue')
  .addStringOption((opt) =>
    opt
      .setName('priority')
      .setDescription('Filter by priority')
      .setRequired(false)
      .addChoices(
        { name: 'Critical', value: 'critical' },
        { name: 'High', value: 'high' },
        { name: 'Medium', value: 'medium' },
        { name: 'Low', value: 'low' },
      ),
  )
  .addBooleanOption((opt) =>
    opt
      .setName('batch')
      .setDescription('Show as batch review (grouped by risk)')
      .setRequired(false),
  );

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

  const priority = interaction.options.getString('priority') ?? undefined;
  const batchMode = interaction.options.getBoolean('batch') ?? false;

  try {
    const tasks = await api.listTasks({
      status: 'pending',
      priority,
      sort: '-priority,-sla_deadline',
      limit: 25,
    });
    const stats = await api.getTaskStats();

    // Batch mode — group by risk
    if (batchMode && tasks.length > 0) {
      const batchItems = tasks.map((task) => ({
        task,
        riskLevel: classifyRisk(task),
      }));
      const embed = buildBatchReviewEmbed(batchItems);
      await interaction.editReply(embed);
      return;
    }

    // Standard queue view
    if (tasks.length === 0) {
      const embed = new EmbedBuilder()
        .setTitle('📥 Decision Queue')
        .setDescription('✅ Queue is empty — no pending decisions!')
        .setColor(COLORS.success)
        .setTimestamp();
      await interaction.editReply({ embeds: [embed] });
      return;
    }

    const lines = tasks.slice(0, 15).map((task, i) => {
      const p = task.priority as Priority;
      const pConfig = PRIORITY_CONFIG[p];
      const slaStr = task.slaBreached
        ? '🚨 BREACHED'
        : task.slaDeadline
          ? `<t:${Math.floor(new Date(task.slaDeadline).getTime() / 1000)}:R>`
          : '';
      return `${i + 1}. ${pConfig.emoji} **${task.title}** ${slaStr}\n   \`${task.id.slice(0, 8)}\` · ${task.type} · ${task.status}`;
    });

    const embed = new EmbedBuilder()
      .setTitle(`📥 Decision Queue (${stats.pending} pending)`)
      .setDescription(lines.join('\n\n'))
      .addFields(
        { name: 'Pending', value: `${stats.pending}`, inline: true },
        { name: 'In Progress', value: `${stats.inProgress}`, inline: true },
        { name: 'SLA Breaches', value: `${stats.slaBreaches}`, inline: true },
        { name: 'Avg Wait', value: `${Math.round(stats.avgWaitTimeMinutes)}m`, inline: true },
      )
      .setColor(stats.slaBreaches > 0 ? COLORS.slaBreach : COLORS.info)
      .setTimestamp();

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

    // Add batch review button if multiple tasks
    const components: ActionRowBuilder<ButtonBuilder>[] = [];
    if (tasks.length > 1) {
      const batchItems = tasks.map((t) => ({ task: t, riskLevel: classifyRisk(t) }));
      const lowRiskIds = batchItems
        .filter((i) => i.riskLevel === 'low')
        .map((i) => i.task.id);

      const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
        new ButtonBuilder()
          .setCustomId(`batch-approve-low:${lowRiskIds.join(',')}`)
          .setLabel(`✅ Approve Low-Risk (${lowRiskIds.length})`)
          .setStyle(ButtonStyle.Success)
          .setDisabled(lowRiskIds.length === 0),
      );
      components.push(row);
    }

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