import {
  EmbedBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  StringSelectMenuBuilder,
  type MessageCreateOptions,
} from 'discord.js';
import { PRIORITY_CONFIG, STAGE_DISPLAY, COLORS, type Priority } from '../config.js';
import type { Task } from '../api-client.js';

interface BatchItem {
  task: Task;
  riskLevel: 'low' | 'medium' | 'high';
}

/**
 * Build a batch review embed — groups similar approvals for efficient review.
 * This is the "5 servers ready for review" pattern from the Master Plan.
 */
export function buildBatchReviewEmbed(items: BatchItem[]): MessageCreateOptions {
  const lowRisk = items.filter((i) => i.riskLevel === 'low');
  const medRisk = items.filter((i) => i.riskLevel === 'medium');
  const highRisk = items.filter((i) => i.riskLevel === 'high');

  const embed = new EmbedBuilder()
    .setTitle(`📋 Batch Review — ${items.length} items ready`)
    .setDescription(
      'Multiple tasks are pending review. Low-risk items can be batch-approved.',
    )
    .setColor(COLORS.action)
    .setTimestamp();

  // Low risk section
  if (lowRisk.length > 0) {
    const lines = lowRisk.map((item) => {
      const ctx = item.task.context;
      const testInfo = ctx.testResults
        ? `✅ ${ctx.testResults.passed}/${ctx.testResults.total} tests`
        : '';
      return `✅ **${item.task.title}** ${testInfo}`;
    });
    embed.addFields({
      name: `🟢 Low Risk (${lowRisk.length})`,
      value: lines.join('\n') || 'None',
    });
  }

  // Medium risk section
  if (medRisk.length > 0) {
    const lines = medRisk.map((item) => {
      const ctx = item.task.context;
      const testInfo = ctx.testResults
        ? `⚠️ ${ctx.testResults.passed}/${ctx.testResults.total} tests`
        : '';
      return `⚠️ **${item.task.title}** ${testInfo}`;
    });
    embed.addFields({
      name: `🟡 Medium Risk (${medRisk.length})`,
      value: lines.join('\n') || 'None',
    });
  }

  // High risk section
  if (highRisk.length > 0) {
    const lines = highRisk.map((item) => {
      const ctx = item.task.context;
      const testInfo = ctx.testResults
        ? `❌ ${ctx.testResults.passed}/${ctx.testResults.total} tests`
        : '';
      return `❌ **${item.task.title}** ${testInfo}`;
    });
    embed.addFields({
      name: `🔴 High Risk (${highRisk.length}) — Review Required`,
      value: lines.join('\n') || 'None',
    });
  }

  // Summary stats
  embed.addFields({
    name: '📊 Summary',
    value: [
      `Total: ${items.length}`,
      `Low Risk: ${lowRisk.length}`,
      `Medium Risk: ${medRisk.length}`,
      `High Risk: ${highRisk.length}`,
    ].join(' · '),
  });

  // Build button row
  const components: Array<ActionRowBuilder<ButtonBuilder | StringSelectMenuBuilder>> = [];

  // Primary action buttons
  const buttonRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
    new ButtonBuilder()
      .setCustomId(`batch-approve-low:${lowRisk.map((i) => i.task.id).join(',')}`)
      .setLabel(`✅ Approve All Low-Risk (${lowRisk.length})`)
      .setStyle(ButtonStyle.Success)
      .setDisabled(lowRisk.length === 0),
    new ButtonBuilder()
      .setCustomId(`batch-approve-all:${items.map((i) => i.task.id).join(',')}`)
      .setLabel(`✅ Approve All (${items.length})`)
      .setStyle(ButtonStyle.Primary),
    new ButtonBuilder()
      .setCustomId('batch-review-individual')
      .setLabel('📋 Review Individually')
      .setStyle(ButtonStyle.Secondary),
  );
  components.push(buttonRow);

  // If there are items to review individually, add a select menu
  if (items.length > 1 && items.length <= 25) {
    const selectMenu = new StringSelectMenuBuilder()
      .setCustomId('batch-select-review')
      .setPlaceholder('Select a task to review...')
      .setMinValues(1)
      .setMaxValues(1)
      .addOptions(
        items.map((item) => ({
          label: truncate(item.task.title, 100),
          description: truncate(item.task.context.summary ?? '', 100),
          value: item.task.id,
          emoji: item.riskLevel === 'low' ? '🟢' : item.riskLevel === 'medium' ? '🟡' : '🔴',
        })),
      );
    components.push(
      new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectMenu),
    );
  }

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

/**
 * Classify a task's risk level based on context.
 */
export function classifyRisk(task: Task): 'low' | 'medium' | 'high' {
  const ctx = task.context;

  // High risk: critical priority, SLA breached, or test failures
  if (task.priority === 'critical' || task.slaBreached) return 'high';
  if (ctx.testResults && ctx.testResults.failed > 0) return 'high';
  if (ctx.testResults && ctx.testResults.coveragePercent < 60) return 'high';

  // Medium risk: high priority, low coverage, or large diffs
  if (task.priority === 'high') return 'medium';
  if (ctx.testResults && ctx.testResults.coveragePercent < 80) return 'medium';
  if (ctx.diffSummary && ctx.diffSummary.filesChanged > 20) return 'medium';

  // Low risk: tests passing, good coverage, small diff
  return 'low';
}

function truncate(str: string, max: number): string {
  return str.length > max ? str.slice(0, max - 3) + '...' : str;
}
