import { router, protectedProcedure, adminProcedure } from "../_core/trpc.ts";
import { z } from 'zod';

export const adminPerformanceRouter = router({
  /**
   * Get admin performance metrics for a time range
   */
  getAdminPerformance: adminProcedure
    .input(
      z.object({
        timeRange: z.enum(['7d', '30d', '90d']),
        adminId: z.number().optional(),
      })
    )
    .query(async ({ input, ctx }) => {
      // Calculate date range
      const now = new Date();
      const daysBack = input.timeRange === '7d' ? 7 : input.timeRange === '30d' ? 30 : 90;
      const startDate = new Date(now.getTime() - daysBack * 24 * 60 * 60 * 1000);

      // Mock data for actions per day
      const actionsPerDay = Array.from({ length: daysBack }, (_, i) => {
        const date = new Date(startDate.getTime() + i * 24 * 60 * 60 * 1000);
        return {
          date: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
          actions: Math.floor(Math.random() * 100) + 20,
        };
      });

      // Mock data for approval times
      const approvalTimes = Array.from({ length: daysBack }, (_, i) => {
        const date = new Date(startDate.getTime() + i * 24 * 60 * 60 * 1000);
        return {
          date: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
          avgTime: Math.floor(Math.random() * 30) + 5,
        };
      });

      // Mock admin stats
      const adminStats = [
        {
          id: 1,
          name: 'Alice Johnson',
          totalActions: 2847,
          avgApprovalTime: 8.5,
          approvalRate: 94.2,
          errorRate: 0.8,
          performanceScore: 92,
        },
        {
          id: 2,
          name: 'Bob Smith',
          totalActions: 2654,
          avgApprovalTime: 9.2,
          approvalRate: 91.5,
          errorRate: 1.2,
          performanceScore: 88,
        },
        {
          id: 3,
          name: 'Carol Davis',
          totalActions: 3102,
          avgApprovalTime: 7.8,
          approvalRate: 96.1,
          errorRate: 0.5,
          performanceScore: 95,
        },
        {
          id: 4,
          name: 'David Wilson',
          totalActions: 2421,
          avgApprovalTime: 10.5,
          approvalRate: 88.3,
          errorRate: 2.1,
          performanceScore: 82,
        },
        {
          id: 5,
          name: 'Emma Brown',
          totalActions: 2789,
          avgApprovalTime: 8.9,
          approvalRate: 93.7,
          errorRate: 1.0,
          performanceScore: 90,
        },
      ];

      // Calculate metrics
      const metrics = {
        avgApprovalTime: adminStats.reduce((sum, a) => sum + a.avgApprovalTime, 0) / adminStats.length,
        totalActionsCompleted: adminStats.reduce((sum, a) => sum + a.totalActions, 0),
        approvalRate: adminStats.reduce((sum, a) => sum + a.approvalRate, 0) / adminStats.length,
        errorRate: adminStats.reduce((sum, a) => sum + a.errorRate, 0) / adminStats.length,
        avgResponseTime: Math.floor(Math.random() * 5) + 1,
      };

      return {
        actionsPerDay,
        approvalTimes,
        adminStats,
        metrics,
      };
    }),

  /**
   * Get list of admins for filtering
   */
  getAdminList: adminProcedure.query(async ({ ctx }) => {
    // Mock admin list
    return [
      { id: 1, name: 'Alice Johnson', role: 'super_admin' },
      { id: 2, name: 'Bob Smith', role: 'admin' },
      { id: 3, name: 'Carol Davis', role: 'admin' },
      { id: 4, name: 'David Wilson', role: 'moderator' },
      { id: 5, name: 'Emma Brown', role: 'finance_team' },
    ];
  }),

  /**
   * Get detailed performance report for an admin
   */
  getAdminDetailedReport: adminProcedure
    .input(z.object({ adminId: z.number() }))
    .query(async ({ input, ctx }) => {
      // Mock detailed report
      return {
        adminId: input.adminId,
        adminName: 'Alice Johnson',
        reportDate: new Date().toISOString(),
        summary: {
          totalActions: 2847,
          approvedCount: 2683,
          rejectedCount: 164,
          avgApprovalTime: 8.5,
          avgResponseTime: 2.3,
          errorRate: 0.8,
          performanceScore: 92,
        },
        breakdown: {
          gameApprovals: { total: 1200, approved: 1150, rejected: 50, avgTime: 7.2 },
          kycReviews: { total: 800, approved: 752, rejected: 48, avgTime: 9.5 },
          paymentProcessing: { total: 600, approved: 600, rejected: 0, avgTime: 8.1 },
          fraudDetection: { total: 247, approved: 181, rejected: 66, avgTime: 10.2 },
        },
        trends: {
          weeklyActions: [245, 267, 289, 301, 295, 312, 338],
          weeklyApprovalRate: [93.2, 93.8, 94.1, 94.5, 94.2, 94.8, 95.1],
          weeklyErrorRate: [1.2, 1.0, 0.9, 0.8, 0.8, 0.7, 0.6],
        },
      };
    }),

  /**
   * Get performance comparison between admins
   */
  getPerformanceComparison: adminProcedure
    .input(
      z.object({
        adminIds: z.array(z.number()),
        metric: z.enum(['approvalRate', 'avgApprovalTime', 'errorRate', 'totalActions']),
      })
    )
    .query(async ({ input, ctx }) => {
      // Mock comparison data
      const adminStats = [
        { id: 1, name: 'Alice Johnson', approvalRate: 94.2, avgApprovalTime: 8.5, errorRate: 0.8, totalActions: 2847 },
        { id: 2, name: 'Bob Smith', approvalRate: 91.5, avgApprovalTime: 9.2, errorRate: 1.2, totalActions: 2654 },
        { id: 3, name: 'Carol Davis', approvalRate: 96.1, avgApprovalTime: 7.8, errorRate: 0.5, totalActions: 3102 },
      ];

      return adminStats.filter((a) => input.adminIds.includes(a.id));
    }),

  /**
   * Export performance report as PDF/CSV
   */
  exportPerformanceReport: adminProcedure
    .input(
      z.object({
        timeRange: z.enum(['7d', '30d', '90d']),
        format: z.enum(['pdf', 'csv']),
        adminIds: z.array(z.number()).optional(),
      })
    )
    .mutation(async ({ input, ctx }) => {
      // Mock export
      return {
        success: true,
        downloadUrl: `/api/reports/performance-${Date.now()}.${input.format}`,
        fileName: `admin-performance-report-${new Date().toISOString().split('T')[0]}.${input.format}`,
      };
    }),

  /**
   * Get performance alerts and insights
   */
  getPerformanceAlerts: adminProcedure.query(async ({ ctx }) => {
    // Mock alerts
    return [
      {
        id: 1,
        type: 'high_error_rate',
        severity: 'warning',
        admin: 'David Wilson',
        message: 'Error rate above 2% threshold',
        timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
      },
      {
        id: 2,
        type: 'slow_approval_time',
        severity: 'info',
        admin: 'Bob Smith',
        message: 'Average approval time increased by 15%',
        timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString(),
      },
      {
        id: 3,
        type: 'high_performance',
        severity: 'success',
        admin: 'Carol Davis',
        message: 'Achieved 96% approval rate this week',
        timestamp: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
      },
    ];
  }),
});
