import { sendEmail } from './brevo.ts';

export interface AdminAlert {
  id: string;
  type: 'fraud' | 'kyc_rejection' | 'payment_failure' | 'system_error' | 'high_risk_user' | 'compliance_issue';
  severity: 'critical' | 'high' | 'medium' | 'low';
  title: string;
  message: string;
  actionUrl?: string;
  timestamp: Date;
  read: boolean;
  adminId: string;
}

export interface NotificationPreferences {
  adminId: string;
  emailOnCritical: boolean;
  emailOnHigh: boolean;
  emailOnMedium: boolean;
  emailOnLow: boolean;
  smsOnCritical: boolean;
  inAppNotifications: boolean;
  digestFrequency: 'immediate' | 'hourly' | 'daily' | 'weekly';
}

class AdminNotificationService {
  private alerts: Map<string, AdminAlert> = new Map();
  private preferences: Map<string, NotificationPreferences> = new Map();

  /**
   * Initialize notification service with default preferences
   */
  initialize(): void {
    console.log('[AdminNotifications] Service initialized');
  }

  /**
   * Create and send a critical alert to admins
   */
  async createAlert(
    type: AdminAlert['type'],
    severity: AdminAlert['severity'],
    title: string,
    message: string,
    adminId: string,
    actionUrl?: string
  ): Promise<AdminAlert> {
    const alert: AdminAlert = {
      id: `alert_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      type,
      severity,
      title,
      message,
      actionUrl,
      timestamp: new Date(),
      read: false,
      adminId,
    };

    this.alerts.set(alert.id, alert);

    // Get admin preferences
    const prefs = this.preferences.get(adminId) || this.getDefaultPreferences(adminId);

    // Send email if enabled for this severity
    if (this.shouldEmailNotify(severity, prefs)) {
      await this.sendAlertEmail(alert, prefs);
    }

    // Send SMS if critical
    if (severity === 'critical' && prefs.smsOnCritical) {
      await this.sendAlertSMS(alert);
    }

    return alert;
  }

  /**
   * Get all alerts for an admin
   */
  getAdminAlerts(adminId: string, unreadOnly = false): AdminAlert[] {
    return Array.from(this.alerts.values())
      .filter((alert) => alert.adminId === adminId && (!unreadOnly || !alert.read))
      .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
  }

  /**
   * Mark alert as read
   */
  markAlertAsRead(alertId: string): void {
    const alert = this.alerts.get(alertId);
    if (alert) {
      alert.read = true;
    }
  }

  /**
   * Mark all alerts as read for an admin
   */
  markAllAlertsAsRead(adminId: string): void {
    Array.from(this.alerts.values())
      .filter((alert) => alert.adminId === adminId && !alert.read)
      .forEach((alert) => {
        alert.read = true;
      });
  }

  /**
   * Delete an alert
   */
  deleteAlert(alertId: string): void {
    this.alerts.delete(alertId);
  }

  /**
   * Update notification preferences
   */
  setPreferences(adminId: string, preferences: Partial<NotificationPreferences>): void {
    const current = this.preferences.get(adminId) || this.getDefaultPreferences(adminId);
    this.preferences.set(adminId, { ...current, ...preferences });
  }

  /**
   * Get notification preferences
   */
  getPreferences(adminId: string): NotificationPreferences {
    return this.preferences.get(adminId) || this.getDefaultPreferences(adminId);
  }

  /**
   * Send alert email
   */
  private async sendAlertEmail(alert: AdminAlert, prefs: NotificationPreferences): Promise<void> {
    try {
      const severityColor = {
        critical: '#ef4444',
        high: '#f97316',
        medium: '#eab308',
        low: '#3b82f6',
      }[alert.severity];

      const emailContent = `
        <h2 style="color: ${severityColor}; margin-bottom: 16px;">
          [${alert.severity.toUpperCase()}] ${alert.title}
        </h2>
        <p style="margin-bottom: 16px; color: #666;">${alert.message}</p>
        <p style="margin-bottom: 16px; color: #999; font-size: 12px;">
          Time: ${alert.timestamp.toLocaleString()}
        </p>
        ${
          alert.actionUrl
            ? `<a href="${alert.actionUrl}" style="display: inline-block; padding: 10px 20px; background-color: ${severityColor}; color: white; text-decoration: none; border-radius: 4px;">View Details</a>`
            : ''
        }
      `;

      await sendEmail({
        to: 'admin@playcoinkrazy.com',
        subject: `[${alert.severity.toUpperCase()}] ${alert.title}`,
        html: emailContent,
      });

      console.log(`[AdminNotifications] Alert email sent for ${alert.id}`);
    } catch (error) {
      console.error('[AdminNotifications] Failed to send alert email:', error);
    }
  }

  /**
   * Send alert SMS (placeholder)
   */
  private async sendAlertSMS(alert: AdminAlert): Promise<void> {
    console.log(`[AdminNotifications] SMS alert would be sent for ${alert.id}`);
    // TODO: Implement SMS sending via Twilio or similar service
  }

  /**
   * Determine if email notification should be sent
   */
  private shouldEmailNotify(severity: AdminAlert['severity'], prefs: NotificationPreferences): boolean {
    switch (severity) {
      case 'critical':
        return prefs.emailOnCritical;
      case 'high':
        return prefs.emailOnHigh;
      case 'medium':
        return prefs.emailOnMedium;
      case 'low':
        return prefs.emailOnLow;
      default:
        return false;
    }
  }

  /**
   * Get default notification preferences
   */
  private getDefaultPreferences(adminId: string): NotificationPreferences {
    return {
      adminId,
      emailOnCritical: true,
      emailOnHigh: true,
      emailOnMedium: false,
      emailOnLow: false,
      smsOnCritical: true,
      inAppNotifications: true,
      digestFrequency: 'immediate',
    };
  }

  /**
   * Get alert statistics
   */
  getAlertStats(adminId: string): {
    total: number;
    unread: number;
    critical: number;
    high: number;
    medium: number;
    low: number;
  } {
    const alerts = Array.from(this.alerts.values()).filter((a) => a.adminId === adminId);

    return {
      total: alerts.length,
      unread: alerts.filter((a) => !a.read).length,
      critical: alerts.filter((a) => a.severity === 'critical').length,
      high: alerts.filter((a) => a.severity === 'high').length,
      medium: alerts.filter((a) => a.severity === 'medium').length,
      low: alerts.filter((a) => a.severity === 'low').length,
    };
  }

  /**
   * Clear old alerts (older than 30 days)
   */
  clearOldAlerts(): number {
    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    let cleared = 0;

    for (const [id, alert] of this.alerts.entries()) {
      if (alert.timestamp < thirtyDaysAgo) {
        this.alerts.delete(id);
        cleared++;
      }
    }

    return cleared;
  }
}

// Export singleton instance
export const adminNotificationService = new AdminNotificationService();
