/**
 * Progress Notification Templates
 *
 * Pre-formatted message templates for progress-related
 * admin notifications on the Telegram backend system.
 */

/**
 * Progress notification data
 */
export interface ProgressNotificationData {
  userId?: string;
  anonymousId: string;
  username?: string;
  moduleName: string;
  moduleType: string;
  percentage: number;
  points: number;
  exercisesCompleted: number;
  totalExercises: number;
  timeSpentMinutes?: number;
  startedAt?: string;
  completedAt?: string;
}

/**
 * Module completion notification data
 */
export interface ModuleCompletionData {
  userId?: string;
  anonymousId: string;
  username?: string;
  moduleName: string;
  moduleType: string;
  finalScore: number;
  totalPoints: number;
  exercisesCompleted: number;
  perfectExercises: number;
  timeSpentMinutes: number;
  startedAt: string;
  completedAt: string;
}

/**
 * Exercise completion notification data
 */
export interface ExerciseCompletionData {
  userId?: string;
  anonymousId: string;
  username?: string;
  moduleName: string;
  exerciseType: string;
  difficulty: string;
  pointsEarned: number;
  timeSpentSeconds: number;
  isCorrect: boolean;
  hintsUsed?: number;
}

/**
 * Generate progress update notification message
 */
export function generateProgressMessage(data: ProgressNotificationData): string {
  const progressEmoji = getProgressEmoji(data.percentage);
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);

  let message = `<b>📈 PROGRESO DE USUARIO</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `📚 <b>Módulo:</b> ${data.moduleName} (${formatModuleType(data.moduleType)})\n`;
  message += `📊 <b>Progreso:</b> ${data.percentage}% ${progressEmoji}\n`;
  message += `⭐ <b>Puntos:</b> ${data.points}\n`;
  message += `✅ <b>Ejercicios:</b> ${data.exercisesCompleted}/${data.totalExercises}\n`;

  if (data.timeSpentMinutes) {
    message += `⏱️ <b>Tiempo:</b> ${formatTime(data.timeSpentMinutes)}\n`;
  }

  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate module completion notification message
 */
export function generateModuleCompletionMessage(data: ModuleCompletionData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const duration = calculateDuration(data.startedAt, data.completedAt);

  let message = `<b>🎓 MÓDULO COMPLETADO</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `📚 <b>Módulo:</b> ${data.moduleName} (${formatModuleType(data.moduleType)})\n`;
  message += `⭐ <b>Puntuación:</b> ${data.finalScore}%\n`;
  message += `🏅 <b>Puntos ganados:</b> ${data.totalPoints}\n`;
  message += `✅ <b>Ejercicios completados:</b> ${data.exercisesCompleted}\n`;

  if (data.perfectExercises > 0) {
    message += `💯 <b>Ejercicios perfectos:</b> ${data.perfectExercises}\n`;
  }

  message += `⏱️ <b>Tiempo total:</b> ${duration}\n`;
  message += `📅 <b>Completado:</b> ${formatDate(data.completedAt)}\n`;
  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate exercise completion notification message
 */
export function generateExerciseCompletionMessage(data: ExerciseCompletionData): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const statusEmoji = data.isCorrect ? '✅' : '❌';

  let message = `<b>📝 EJERCICIO COMPLETADO</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${data.anonymousId}\n`;
  message += `📚 <b>Módulo:</b> ${data.moduleName}\n`;
  message += `🔷 <b>Tipo:</b> ${formatExerciseType(data.exerciseType)}\n`;
  message += `📊 <b>Dificultad:</b> ${formatDifficulty(data.difficulty)}\n`;
  message += `📌 <b>Resultado:</b> ${statusEmoji}\n`;
  message += `⭐ <b>Puntos:</b> +${data.pointsEarned}\n`;
  message += `⏱️ <b>Tiempo:</b> ${data.timeSpentSeconds}s\n`;

  if (data.hintsUsed !== undefined && data.hintsUsed > 0) {
    message += `💡 <b>Pistas usadas:</b> ${data.hintsUsed}\n`;
  }

  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate streak notification message
 */
export function generateStreakMessage(
  anonymousId: string,
  streakDays: number,
  currentStreakExercises: number
): string {
  const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
  const streakEmoji = streakDays >= 30 ? '🔥🔥🔥' : streakDays >= 7 ? '🔥🔥' : '🔥';

  let message = `<b>🔥 RACHA DE USUARIO</b>\n\n`;
  message += `👤 <b>Usuario:</b> ${anonymousId}\n`;
  message += `${streakEmoji} <b>Días de racha:</b> ${streakDays}\n`;
  message += `✅ <b>Ejercicios hoy:</b> ${currentStreakExercises}\n`;
  message += `\n⏰ <i>${timestamp}</i>`;

  return message;
}

/**
 * Generate progress summary for daily summary
 */
export function generateProgressSummary(
  totalUsers: number,
  activeUsers: number,
  modulesCompletedToday: number,
  averageProgress: number
): string {
  let message = `<b>📊 RESUMEN DE PROGRESO</b>\n\n`;
  message += `👥 <b>Usuarios totales:</b> ${totalUsers}\n`;
  message += `🟢 <b>Usuarios activos hoy:</b> ${activeUsers} (${((activeUsers / totalUsers) * 100).toFixed(1)}%)\n`;
  message += `📚 <b>Módulos completados hoy:</b> ${modulesCompletedToday}\n`;
  message += `📈 <b>Progreso promedio:</b> ${averageProgress.toFixed(1)}%\n`;

  return message;
}

/**
 * Helper: Get progress emoji based on percentage
 */
function getProgressEmoji(percentage: number): string {
  if (percentage >= 100) return '🎉';
  if (percentage >= 75) return '📈';
  if (percentage >= 50) return '📊';
  if (percentage >= 25) return '📉';
  return '🔄';
}

/**
 * Helper: Format module type
 */
function formatModuleType(type: string): string {
  const types: Record<string, string> = {
    'FUNDAMENTOS': 'Fundamentos',
    'SISTEMAS_ESPACIOS': 'Sistemas y Espacios',
    'APLICACIONES': 'Aplicaciones',
  };
  return types[type] || type;
}

/**
 * Helper: Format exercise type
 */
function formatExerciseType(type: string): string {
  const types: Record<string, string> = {
    'MULTIPLE_CHOICE': 'Opción Múltiple',
    'OPEN_RESPONSE': 'Respuesta Abierta',
    'CALCULATION': 'Cálculo',
    'PROOF': 'Demostración',
    'TRUE_FALSE': 'Verdadero/Falso',
  };
  return types[type] || type;
}

/**
 * Helper: Format difficulty
 */
function formatDifficulty(difficulty: string): string {
  const difficulties: Record<string, string> = {
    'BASIC': 'Básico',
    'INTERMEDIATE': 'Intermedio',
    'ADVANCED': 'Avanzado',
    'EXPERT': 'Experto',
  };
  return difficulties[difficulty] || difficulty;
}

/**
 * Helper: Format time in minutes
 */
function formatTime(minutes: number): string {
  if (minutes < 60) {
    return `${minutes}min`;
  }
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return mins > 0 ? `${hours}h ${mins}min` : `${hours}h`;
}

/**
 * Helper: Calculate duration between two dates
 */
function calculateDuration(startedAt: string, completedAt: string): string {
  const start = new Date(startedAt);
  const end = new Date(completedAt);
  const diffMs = end.getTime() - start.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  return formatTime(diffMins);
}

/**
 * Helper: Format date
 */
function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('es-ES', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

/**
 * Message type constants
 */
export const PROGRESS_MESSAGE_TYPES = {
  MODULE_COMPLETED: 'MODULE_COMPLETED',
  EXERCISE_COMPLETED: 'EXERCISE_COMPLETED',
  STREAK_MILESTONE: 'STREAK_MILESTONE',
} as const;
