/**
 * Report Template Marketplace
 * Pre-built report templates for common use cases
 */

export interface ReportTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  type: 'payment' | 'reconciliation' | 'fraud' | 'withdrawal' | 'analytics';
  frequency: 'daily' | 'weekly' | 'monthly';
  metrics: string[];
  filters: Record<string, string[]>;
  defaultRecipients: number;
  popularity: number;
  rating: number;
  usageCount: number;
  createdBy: string;
  isOfficial: boolean;
}

export interface TemplateCategory {
  id: string;
  name: string;
  description: string;
  icon: string;
  templateCount: number;
}

/**
 * Official Report Templates
 */
export const officialTemplates: ReportTemplate[] = [
  {
    id: 'TEMPLATE-REVENUE-DAILY',
    name: 'Daily Revenue Summary',
    description: 'Daily revenue breakdown by payment method with trends',
    category: 'Revenue Analysis',
    type: 'payment',
    frequency: 'daily',
    metrics: ['totalRevenue', 'transactionCount', 'averageTransaction', 'successRate'],
    filters: { paymentMethods: ['all'], timeRange: ['24h'] },
    defaultRecipients: 5,
    popularity: 95,
    rating: 4.8,
    usageCount: 1250,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-REVENUE-WEEKLY',
    name: 'Weekly Revenue Report',
    description: 'Comprehensive weekly revenue analysis with comparisons',
    category: 'Revenue Analysis',
    type: 'payment',
    frequency: 'weekly',
    metrics: ['totalRevenue', 'weekOverWeekGrowth', 'paymentMethodBreakdown', 'topPlayers'],
    filters: { paymentMethods: ['all'], timeRange: ['7d'] },
    defaultRecipients: 5,
    popularity: 92,
    rating: 4.7,
    usageCount: 980,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-FRAUD-DAILY',
    name: 'Daily Fraud Alert Report',
    description: 'Real-time fraud detection alerts and suspicious activity',
    category: 'Fraud Detection',
    type: 'fraud',
    frequency: 'daily',
    metrics: ['fraudScore', 'suspiciousTransactions', 'blockedPayments', 'riskLevel'],
    filters: { minFraudScore: ['0.5'], timeRange: ['24h'] },
    defaultRecipients: 3,
    popularity: 88,
    rating: 4.6,
    usageCount: 850,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-RECONCILIATION-WEEKLY',
    name: 'Weekly Reconciliation Report',
    description: 'Payment provider reconciliation with discrepancy analysis',
    category: 'Reconciliation',
    type: 'reconciliation',
    frequency: 'weekly',
    metrics: ['matchRate', 'discrepancies', 'totalRecords', 'resolutionStatus'],
    filters: { providers: ['all'], timeRange: ['7d'] },
    defaultRecipients: 3,
    popularity: 85,
    rating: 4.5,
    usageCount: 720,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-PLAYER-RETENTION',
    name: 'Player Retention Analysis',
    description: 'Monthly player retention metrics and churn analysis',
    category: 'Player Analytics',
    type: 'analytics',
    frequency: 'monthly',
    metrics: ['activeUsers', 'retentionRate', 'churnRate', 'lifetimeValue'],
    filters: { cohorts: ['all'], timeRange: ['30d'] },
    defaultRecipients: 4,
    popularity: 82,
    rating: 4.4,
    usageCount: 650,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-WITHDRAWAL-WEEKLY',
    name: 'Weekly Withdrawal Summary',
    description: 'Withdrawal requests, approvals, and payout status',
    category: 'Withdrawals',
    type: 'withdrawal',
    frequency: 'weekly',
    metrics: ['totalRequests', 'approvedAmount', 'pendingAmount', 'averageProcessingTime'],
    filters: { status: ['all'], timeRange: ['7d'] },
    defaultRecipients: 3,
    popularity: 78,
    rating: 4.3,
    usageCount: 580,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-EXECUTIVE-MONTHLY',
    name: 'Executive Monthly Dashboard',
    description: 'High-level KPIs for executive review',
    category: 'Executive',
    type: 'analytics',
    frequency: 'monthly',
    metrics: ['totalRevenue', 'activeUsers', 'retentionRate', 'fraudRate', 'customerSatisfaction'],
    filters: { scope: ['all'] },
    defaultRecipients: 2,
    popularity: 75,
    rating: 4.2,
    usageCount: 500,
    createdBy: 'system',
    isOfficial: true,
  },
  {
    id: 'TEMPLATE-PAYMENT-METHOD-ANALYSIS',
    name: 'Payment Method Analysis',
    description: 'Detailed breakdown of each payment method performance',
    category: 'Payment Analysis',
    type: 'payment',
    frequency: 'weekly',
    metrics: ['methodBreakdown', 'successRate', 'averageFee', 'volumeTrend'],
    filters: { methods: ['all'], timeRange: ['7d'] },
    defaultRecipients: 3,
    popularity: 72,
    rating: 4.1,
    usageCount: 450,
    createdBy: 'system',
    isOfficial: true,
  },
];

/**
 * Template Categories
 */
export const templateCategories: TemplateCategory[] = [
  {
    id: 'CAT-REVENUE',
    name: 'Revenue Analysis',
    description: 'Payment and revenue tracking reports',
    icon: 'TrendingUp',
    templateCount: 3,
  },
  {
    id: 'CAT-FRAUD',
    name: 'Fraud Detection',
    description: 'Fraud alerts and security reports',
    icon: 'AlertTriangle',
    templateCount: 2,
  },
  {
    id: 'CAT-RECONCILIATION',
    name: 'Reconciliation',
    description: 'Payment provider reconciliation',
    icon: 'CheckCircle',
    templateCount: 1,
  },
  {
    id: 'CAT-PLAYER',
    name: 'Player Analytics',
    description: 'Player behavior and retention',
    icon: 'Users',
    templateCount: 2,
  },
  {
    id: 'CAT-WITHDRAWAL',
    name: 'Withdrawals',
    description: 'Withdrawal management reports',
    icon: 'Send',
    templateCount: 1,
  },
  {
    id: 'CAT-EXECUTIVE',
    name: 'Executive',
    description: 'High-level KPI dashboards',
    icon: 'BarChart3',
    templateCount: 1,
  },
];

/**
 * Get all official templates
 */
export function getOfficialTemplates(): ReportTemplate[] {
  return officialTemplates;
}

/**
 * Get templates by category
 */
export function getTemplatesByCategory(category: string): ReportTemplate[] {
  return officialTemplates.filter(t => t.category === category);
}

/**
 * Get templates by type
 */
export function getTemplatesByType(type: string): ReportTemplate[] {
  return officialTemplates.filter(t => t.type === type);
}

/**
 * Get popular templates
 */
export function getPopularTemplates(limit: number = 5): ReportTemplate[] {
  return [...officialTemplates]
    .sort((a, b) => b.popularity - a.popularity)
    .slice(0, limit);
}

/**
 * Get top-rated templates
 */
export function getTopRatedTemplates(limit: number = 5): ReportTemplate[] {
  return [...officialTemplates]
    .sort((a, b) => b.rating - a.rating)
    .slice(0, limit);
}

/**
 * Get template by ID
 */
export function getTemplateById(id: string): ReportTemplate | undefined {
  return officialTemplates.find(t => t.id === id);
}

/**
 * Search templates
 */
export function searchTemplates(query: string): ReportTemplate[] {
  const lowerQuery = query.toLowerCase();
  return officialTemplates.filter(
    t =>
      t.name.toLowerCase().includes(lowerQuery) ||
      t.description.toLowerCase().includes(lowerQuery) ||
      t.category.toLowerCase().includes(lowerQuery)
  );
}

/**
 * Get template statistics
 */
export function getTemplateStats() {
  return {
    totalTemplates: officialTemplates.length,
    totalCategories: templateCategories.length,
    totalUsage: officialTemplates.reduce((sum, t) => sum + t.usageCount, 0),
    averageRating: (
      officialTemplates.reduce((sum, t) => sum + t.rating, 0) / officialTemplates.length
    ).toFixed(1),
    mostPopular: officialTemplates.reduce((max, t) => (t.popularity > max.popularity ? t : max)),
    mostUsed: officialTemplates.reduce((max, t) => (t.usageCount > max.usageCount ? t : max)),
  };
}

/**
 * Get template recommendations
 */
export function getTemplateRecommendations(userRole: string): ReportTemplate[] {
  const recommendations: Record<string, string[]> = {
    admin: ['TEMPLATE-EXECUTIVE-MONTHLY', 'TEMPLATE-REVENUE-WEEKLY', 'TEMPLATE-FRAUD-DAILY'],
    finance: ['TEMPLATE-REVENUE-DAILY', 'TEMPLATE-RECONCILIATION-WEEKLY', 'TEMPLATE-PAYMENT-METHOD-ANALYSIS'],
    security: ['TEMPLATE-FRAUD-DAILY', 'TEMPLATE-REVENUE-WEEKLY'],
    operations: ['TEMPLATE-WITHDRAWAL-WEEKLY', 'TEMPLATE-PLAYER-RETENTION', 'TEMPLATE-RECONCILIATION-WEEKLY'],
  };

  const templateIds = recommendations[userRole] || recommendations['admin'];
  return templateIds
    .map(id => getTemplateById(id))
    .filter((t): t is ReportTemplate => t !== undefined);
}

/**
 * Create custom template from official
 */
export function createCustomTemplateFromOfficial(
  templateId: string,
  customizations: Partial<ReportTemplate>
): ReportTemplate | null {
  const official = getTemplateById(templateId);
  if (!official) return null;

  return {
    ...official,
    id: `CUSTOM-${Date.now()}`,
    name: customizations.name || `${official.name} (Custom)`,
    description: customizations.description || official.description,
    metrics: customizations.metrics || official.metrics,
    filters: customizations.filters || official.filters,
    isOfficial: false,
    usageCount: 0,
    createdBy: customizations.createdBy || 'user',
  };
}

/**
 * Get template preview
 */
export function getTemplatePreview(templateId: string) {
  const template = getTemplateById(templateId);
  if (!template) return null;

  return {
    template,
    preview: {
      title: template.name,
      description: template.description,
      frequency: template.frequency,
      metrics: template.metrics,
      sampleData: generateSampleData(template.type),
    },
  };
}

/**
 * Generate sample data for template preview
 */
function generateSampleData(type: string): Record<string, any> {
  switch (type) {
    case 'payment':
      return {
        totalRevenue: '$125,000',
        transactionCount: '2,500',
        successRate: '94.5%',
        averageTransaction: '$50',
      };
    case 'fraud':
      return {
        fraudScore: '1.2%',
        suspiciousTransactions: '30',
        blockedPayments: '5',
        riskLevel: 'Low',
      };
    case 'reconciliation':
      return {
        matchRate: '99%',
        discrepancies: '50',
        totalRecords: '5,000',
        resolutionStatus: 'In Progress',
      };
    case 'withdrawal':
      return {
        totalRequests: '500',
        approvedAmount: '$50,000',
        pendingAmount: '$5,000',
        averageProcessingTime: '2.5 hours',
      };
    default:
      return {
        activeUsers: '10,000',
        retentionRate: '65%',
        churnRate: '5%',
        lifetimeValue: '$250',
      };
  }
}

/**
 * Rate template
 */
export function rateTemplate(templateId: string, rating: number): boolean {
  const template = getTemplateById(templateId);
  if (!template) return false;

  // In production, update database
  console.log(`[Template Marketplace] Rated template ${templateId} with ${rating} stars`);
  return true;
}

/**
 * Get template feedback
 */
export function getTemplateFeedback(templateId: string) {
  return {
    templateId,
    averageRating: 4.5,
    totalRatings: 250,
    feedback: [
      { rating: 5, comment: 'Exactly what we needed!', user: 'admin1' },
      { rating: 4, comment: 'Good but needs more metrics', user: 'admin2' },
      { rating: 5, comment: 'Saves us hours every week', user: 'admin3' },
    ],
  };
}
