import {
  EmbedBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  type MessageCreateOptions,
} from 'discord.js';
import { COLORS, PRIORITY_CONFIG, type Priority } from '../config.js';

interface SlaWarningData {
  taskId: string;
  taskTitle: string;
  pipelineId: string | null;
  pipelineName?: string;
  slaDeadline: string;
  minutesRemaining: number;
  escalationLevel: number;
  priority?: string;
}

/**
 * Build an SLA warning embed — posted to #factory-alerts.
 * Includes @here mention for urgency.
 */
export function buildSlaWarningEmbed(data: SlaWarningData): MessageCreateOptions {
  const isBreached = data.minutesRemaining <= 0;
  const priority = (data.priority ?? 'high') as Priority;
  const pConfig = PRIORITY_CONFIG[priority];

  const timeStr = isBreached
    ? `🚨 **BREACHED** (${Math.abs(Math.round(data.minutesRemaining))}m overdue)`
    : `⚠️ ${Math.round(data.minutesRemaining)}m remaining`;

  const escalationStr = data.escalationLevel > 0
    ? `Level ${data.escalationLevel} — ${getEscalationDescription(data.escalationLevel)}`
    : 'Initial warning';

  const embed = new EmbedBuilder()
    .setTitle(isBreached ? '🚨 SLA BREACHED' : '⚠️ SLA Warning')
    .setDescription(
      `**${data.taskTitle}**\n\n` +
      `${isBreached ? 'This task has exceeded its SLA deadline.' : 'This task is approaching its SLA deadline.'}\n` +
      `Immediate action required.`,
    )
    .addFields(
      { name: 'Pipeline', value: data.pipelineName ?? data.pipelineId ?? 'N/A', inline: true },
      { name: 'Priority', value: `${pConfig.emoji} ${pConfig.label}`, inline: true },
      { name: 'Time', value: timeStr, inline: true },
      { name: 'Deadline', value: `<t:${Math.floor(new Date(data.slaDeadline).getTime() / 1000)}:R>`, inline: true },
      { name: 'Escalation', value: escalationStr, inline: true },
    )
    .setColor(isBreached ? COLORS.slaBreach : COLORS.slaWarning)
    .setFooter({ text: `Task ID: ${data.taskId}` })
    .setTimestamp();

  const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
    new ButtonBuilder()
      .setCustomId(`approve:${data.taskId}`)
      .setLabel('✅ Approve Now')
      .setStyle(ButtonStyle.Success),
    new ButtonBuilder()
      .setCustomId(`reject:${data.taskId}`)
      .setLabel('❌ Reject')
      .setStyle(ButtonStyle.Danger),
    new ButtonBuilder()
      .setCustomId(`details:${data.taskId}`)
      .setLabel('📋 Details')
      .setStyle(ButtonStyle.Secondary),
  );

  // @here for warnings, @everyone for breaches
  const mention = isBreached ? '@everyone' : '@here';

  return {
    content: `${mention} — ${isBreached ? 'SLA BREACHED' : 'SLA Warning'}: **${data.taskTitle}**`,
    embeds: [embed],
    components: [buttons],
  };
}

/**
 * Build a critical escalation embed — only for T+SLA+2h situations.
 */
export function buildCriticalEscalationEmbed(data: SlaWarningData): MessageCreateOptions {
  const embed = new EmbedBuilder()
    .setTitle('🚨🚨🚨 CRITICAL — Immediate Action Required')
    .setDescription(
      `**${data.taskTitle}**\n\n` +
      `This task has been breached for ${Math.abs(Math.round(data.minutesRemaining))} minutes.\n` +
      `All escalation paths have been triggered. Human intervention is **required immediately**.`,
    )
    .addFields(
      { name: 'Pipeline', value: data.pipelineName ?? data.pipelineId ?? 'N/A', inline: true },
      { name: 'Overdue By', value: `${Math.abs(Math.round(data.minutesRemaining))}m`, inline: true },
      { name: 'Escalation', value: `Level ${data.escalationLevel}`, inline: true },
    )
    .setColor(COLORS.slaBreach)
    .setTimestamp();

  const buttons = new ActionRowBuilder<ButtonBuilder>().addComponents(
    new ButtonBuilder()
      .setCustomId(`approve:${data.taskId}`)
      .setLabel('✅ APPROVE NOW')
      .setStyle(ButtonStyle.Success),
    new ButtonBuilder()
      .setCustomId(`reject:${data.taskId}`)
      .setLabel('❌ REJECT')
      .setStyle(ButtonStyle.Danger),
  );

  return {
    content: `@everyone 🚨 **CRITICAL ESCALATION** — ${data.taskTitle}`,
    embeds: [embed],
    components: [buttons],
  };
}

function getEscalationDescription(level: number): string {
  switch (level) {
    case 1: return 'DM reminder sent';
    case 2: return 'Channel mention escalation';
    case 3: return '@here alert triggered';
    case 4: return 'Full escalation — @everyone + SMS';
    default: return `Escalation tier ${level}`;
  }
}
