/**
 * FYI Popup System
 * Admin-managed announcements displayed once per user on login
 */

export interface FYIPopup {
  id: number;
  title: string;
  content: string;
  htmlContent?: string;
  type: 'feature' | 'update' | 'maintenance' | 'announcement' | 'event';
  icon?: string;
  backgroundColor?: string;
  textColor?: string;
  buttonText?: string;
  buttonLink?: string;
  imageUrl?: string;
  priority: 'low' | 'medium' | 'high' | 'critical';
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
  expiresAt?: Date;
  version: number;
}

export interface UserFYIStatus {
  userId: number;
  fyiId: number;
  viewed: boolean;
  viewedAt?: Date;
  dismissed: boolean;
  dismissedAt?: Date;
}

export interface FYIPopupHistory {
  id: number;
  fyiId: number;
  previousVersion: number;
  newVersion: number;
  changedBy: number;
  changedAt: Date;
  changes: string;
}

/**
 * Create new FYI popup
 */
export function createFYIPopup(
  title: string,
  content: string,
  type: string,
  priority: string
): Partial<FYIPopup> {
  return {
    title,
    content,
    type: type as any,
    priority: priority as any,
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    version: 1,
  };
}

/**
 * Update FYI popup
 */
export function updateFYIPopup(
  popup: FYIPopup,
  updates: Partial<FYIPopup>
): FYIPopup {
  const updated = {
    ...popup,
    ...updates,
    updatedAt: new Date(),
    version: popup.version + 1,
  };
  return updated;
}

/**
 * Check if user has seen current FYI popup
 */
export function hasUserSeenFYI(
  userStatuses: UserFYIStatus[],
  fyiId: number
): boolean {
  const status = userStatuses.find(s => s.fyiId === fyiId);
  return status?.viewed || false;
}

/**
 * Mark FYI as viewed by user
 */
export function markFYIAsViewed(
  userId: number,
  fyiId: number
): UserFYIStatus {
  return {
    userId,
    fyiId,
    viewed: true,
    viewedAt: new Date(),
    dismissed: false,
  };
}

/**
 * Dismiss FYI popup
 */
export function dismissFYIPopup(
  userId: number,
  fyiId: number
): UserFYIStatus {
  return {
    userId,
    fyiId,
    viewed: true,
    viewedAt: new Date(),
    dismissed: true,
    dismissedAt: new Date(),
  };
}

/**
 * Get active FYI popups
 */
export function getActiveFYIPopups(popups: FYIPopup[]): FYIPopup[] {
  const now = new Date();
  return popups.filter(
    popup =>
      popup.isActive &&
      (!popup.expiresAt || popup.expiresAt > now)
  );
}

/**
 * Get FYI popup to show on login
 */
export function getFYIPopupForLogin(
  popups: FYIPopup[],
  userStatuses: UserFYIStatus[]
): FYIPopup | null {
  const activePopups = getActiveFYIPopups(popups);

  // Sort by priority (critical > high > medium > low) and by newest first
  const sorted = activePopups.sort((a, b) => {
    const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
    const priorityDiff =
      priorityOrder[a.priority as keyof typeof priorityOrder] -
      priorityOrder[b.priority as keyof typeof priorityOrder];

    if (priorityDiff !== 0) return priorityDiff;
    return b.updatedAt.getTime() - a.updatedAt.getTime();
  });

  // Find first popup that hasn't been viewed by this user
  // Actually, we want to show the latest version that hasn't been seen
  for (const popup of sorted) {
    if (!hasUserSeenFYI(userStatuses, popup.id)) {
      return popup;
    }
  }

  return null;
}

/**
 * Generate HTML for FYI popup
 */
export function generateFYIPopupHTML(popup: FYIPopup): string {
  const bgColor = popup.backgroundColor || '#1e293b';
  const textColor = popup.textColor || '#ffffff';
  const icon = getIconForType(popup.type);

  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
    .popup-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 9999; }
    .popup-container { background: ${bgColor}; color: ${textColor}; border-radius: 12px; padding: 32px; max-width: 500px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3); }
    .popup-header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
    .popup-icon { font-size: 32px; }
    .popup-title { font-size: 24px; font-weight: bold; margin: 0; }
    .popup-content { font-size: 16px; line-height: 1.6; margin: 16px 0; }
    .popup-image { width: 100%; border-radius: 8px; margin: 16px 0; }
    .popup-actions { display: flex; gap: 12px; margin-top: 24px; }
    .popup-button { padding: 10px 20px; border-radius: 6px; border: none; font-size: 14px; font-weight: 600; cursor: pointer; }
    .popup-button-primary { background: #3b82f6; color: white; flex: 1; }
    .popup-button-primary:hover { background: #2563eb; }
    .popup-button-secondary { background: transparent; color: ${textColor}; border: 1px solid ${textColor}; }
    .popup-button-secondary:hover { background: rgba(255,255,255,0.1); }
    .popup-badge { display: inline-block; background: ${popup.priority === 'critical' ? '#ef4444' : popup.priority === 'high' ? '#f97316' : '#eab308'}; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; margin-bottom: 12px; }
  </style>
</head>
<body>
  <div class="popup-overlay">
    <div class="popup-container">
      <div class="popup-badge">${popup.priority.toUpperCase()}</div>
      <div class="popup-header">
        <div class="popup-icon">${icon}</div>
        <h2 class="popup-title">${popup.title}</h2>
      </div>
      ${popup.imageUrl ? `<img src="${popup.imageUrl}" class="popup-image" alt="FYI">` : ''}
      <div class="popup-content">${popup.htmlContent || popup.content}</div>
      <div class="popup-actions">
        ${popup.buttonLink ? `<button class="popup-button popup-button-primary" onclick="window.location.href='${popup.buttonLink}'">${popup.buttonText || 'Learn More'}</button>` : ''}
        <button class="popup-button popup-button-secondary" onclick="dismissPopup()">Got it</button>
      </div>
    </div>
  </div>
  <script>
    function dismissPopup() {
      // Trigger dismiss event
      window.parent.postMessage({ type: 'FYI_DISMISSED' }, '*');
    }
  </script>
</body>
</html>
  `;
}

/**
 * Get icon for FYI type
 */
export function getIconForType(type: string): string {
  const icons: Record<string, string> = {
    feature: '✨',
    update: '🔄',
    maintenance: '🔧',
    announcement: '📢',
    event: '🎉',
  };
  return icons[type] || '📌';
}

/**
 * Get color for priority
 */
export function getColorForPriority(priority: string): {
  bg: string;
  text: string;
} {
  const colors: Record<string, { bg: string; text: string }> = {
    critical: { bg: '#7f1d1d', text: '#fecaca' },
    high: { bg: '#7c2d12', text: '#fed7aa' },
    medium: { bg: '#3f3f00', text: '#fef08a' },
    low: { bg: '#1e3a8a', text: '#bfdbfe' },
  };
  return colors[priority] || colors.low;
}

/**
 * Create FYI popup history entry
 */
export function createFYIHistory(
  fyiId: number,
  previousVersion: number,
  newVersion: number,
  changedBy: number,
  changes: string
): Partial<FYIPopupHistory> {
  return {
    fyiId,
    previousVersion,
    newVersion,
    changedBy,
    changedAt: new Date(),
    changes,
  };
}

/**
 * Validate FYI popup data
 */
export function validateFYIPopup(
  popup: Partial<FYIPopup>
): { valid: boolean; errors: string[] } {
  const errors: string[] = [];

  if (!popup.title || popup.title.trim().length < 3) {
    errors.push('Title must be at least 3 characters');
  }

  if (!popup.content || popup.content.trim().length < 10) {
    errors.push('Content must be at least 10 characters');
  }

  if (!popup.type || !['feature', 'update', 'maintenance', 'announcement', 'event'].includes(popup.type)) {
    errors.push('Invalid popup type');
  }

  if (!popup.priority || !['low', 'medium', 'high', 'critical'].includes(popup.priority)) {
    errors.push('Invalid priority level');
  }

  return {
    valid: errors.length === 0,
    errors,
  };
}

/**
 * Get FYI statistics
 */
export function getFYIStatistics(
  popup: FYIPopup,
  userStatuses: UserFYIStatus[]
): {
  totalUsers: number;
  viewedCount: number;
  dismissedCount: number;
  viewRate: number;
} {
  const popupStatuses = userStatuses.filter(s => s.fyiId === popup.id);
  const viewedCount = popupStatuses.filter(s => s.viewed).length;
  const dismissedCount = popupStatuses.filter(s => s.dismissed).length;
  const totalUsers = popupStatuses.length;
  const viewRate = totalUsers > 0 ? (viewedCount / totalUsers) * 100 : 0;

  return {
    totalUsers,
    viewedCount,
    dismissedCount,
    viewRate: Math.round(viewRate * 100) / 100,
  };
}

/**
 * Archive old FYI popups
 */
export function archiveOldFYIPopups(
  popups: FYIPopup[],
  daysOld: number = 30
): FYIPopup[] {
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - daysOld);

  return popups.map(popup => {
    if (popup.updatedAt < cutoffDate && popup.isActive) {
      return { ...popup, isActive: false };
    }
    return popup;
  });
}
