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

export const adminCoachingRouter = router({
  /**
   * Get personalized coaching profile for an admin
   */
  getCoachingProfile: protectedProcedure.query(async ({ ctx }) => {
    const adminId = ctx.user?.id;

    // Mock coaching profile data
    const coachingProfile = {
      adminId,
      adminName: 'Current Admin',
      role: 'admin',
      joinDate: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000),
      performanceScore: 82,
      strengths: ['communication', 'decision_quality', 'consistency'],
      improvementAreas: ['approval_speed', 'workload_management'],
      performanceData: Array.from({ length: 30 }, (_, i) => ({
        date: new Date(Date.now() - (30 - i) * 24 * 60 * 60 * 1000).toLocaleDateString(),
        score: 75 + Math.random() * 15,
      })),
      stats: {
        totalRecommendations: 5,
        activeRecommendations: 3,
        completedRecommendations: 2,
        recommendationCompletionRate: 40,
        totalTrainingsCompleted: 8,
        averageTrainingRating: 4.6,
        improvementTrend: 12.5,
        estimatedPerformanceGain: 18,
        coachingEngagementScore: 78,
      },
    };

    return coachingProfile;
  }),

  /**
   * Get coaching recommendations for an admin
   */
  getCoachingRecommendations: protectedProcedure
    .input(z.object({ area: z.string().optional() }))
    .query(async ({ ctx, input }) => {
      // Mock recommendations
      const recommendations = [
        {
          id: 'rec_001',
          adminId: ctx.user?.id,
          area: 'approval_speed',
          title: 'Accelerate Approval Process',
          description: 'Your approval time is 25% above team average. Let\'s work on streamlining your workflow.',
          priority: 'high',
          targetMetric: 'Average Approval Time',
          currentValue: 9.5,
          targetValue: 7.5,
          estimatedTimeToImprove: 14,
          actionItems: [
            'Review your current approval checklist - identify non-essential steps',
            'Set daily approval targets (e.g., 50 approvals/day)',
            'Use batch processing for similar items',
            'Implement keyboard shortcuts for common actions',
          ],
          relatedResources: ['tr_001'],
          createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
          targetDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
          status: 'active',
        },
        {
          id: 'rec_002',
          adminId: ctx.user?.id,
          area: 'workload_management',
          title: 'Manage Workload Effectively',
          description: 'Balance your workload to maintain quality and avoid burnout.',
          priority: 'medium',
          targetMetric: 'Workload Balance',
          currentValue: 65,
          targetValue: 85,
          estimatedTimeToImprove: 21,
          actionItems: [
            'Prioritize high-impact tasks',
            'Delegate routine work to junior staff',
            'Take regular breaks throughout the day',
            'Use time management tools and techniques',
          ],
          relatedResources: ['tr_004'],
          createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
          targetDate: new Date(Date.now() + 21 * 24 * 60 * 60 * 1000),
          status: 'active',
        },
        {
          id: 'rec_003',
          adminId: ctx.user?.id,
          area: 'accuracy',
          title: 'Improve Decision Accuracy',
          description: 'Your error rate is higher than expected. Let\'s focus on quality over speed.',
          priority: 'critical',
          targetMetric: 'Error Rate',
          currentValue: 2.1,
          targetValue: 0.8,
          estimatedTimeToImprove: 28,
          actionItems: [
            'Implement a double-check process for critical decisions',
            'Review recent errors to identify patterns',
            'Take accuracy-focused training',
            'Reduce daily workload to improve focus',
          ],
          relatedResources: ['tr_002'],
          createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
          targetDate: new Date(Date.now() + 28 * 24 * 60 * 60 * 1000),
          status: 'active',
        },
      ];

      if (input.area) {
        return recommendations.filter((r) => r.area === input.area);
      }

      return recommendations;
    }),

  /**
   * Get training resources
   */
  getTrainingResources: protectedProcedure.query(async ({ ctx }) => {
    return [
      {
        id: 'tr_001',
        title: 'Approval Process Optimization',
        description: 'Learn techniques to streamline your approval workflow and reduce processing time.',
        type: 'video',
        category: 'approval_speed',
        duration: 15,
        difficulty: 'beginner',
        url: 'https://example.com/training/approval-optimization',
        tags: ['workflow', 'efficiency', 'process'],
        completionRate: 0,
        rating: 4.5,
      },
      {
        id: 'tr_002',
        title: 'Fraud Detection Best Practices',
        description: 'Master the techniques for identifying and preventing fraudulent activities.',
        type: 'guide',
        category: 'accuracy',
        duration: 30,
        difficulty: 'intermediate',
        url: 'https://example.com/training/fraud-detection',
        tags: ['security', 'fraud', 'detection'],
        completionRate: 0,
        rating: 4.8,
      },
      {
        id: 'tr_003',
        title: 'Decision Making Framework',
        description: 'Develop a structured approach to making consistent, high-quality decisions.',
        type: 'article',
        category: 'decision_quality',
        duration: 20,
        difficulty: 'intermediate',
        url: 'https://example.com/training/decision-framework',
        tags: ['decision', 'framework', 'quality'],
        completionRate: 0,
        rating: 4.6,
      },
      {
        id: 'tr_004',
        title: 'Time Management Mastery',
        description: 'Optimize your time management to handle workload effectively.',
        type: 'webinar',
        category: 'workload_management',
        duration: 45,
        difficulty: 'beginner',
        url: 'https://example.com/training/time-management',
        tags: ['time', 'management', 'productivity'],
        completionRate: 0,
        rating: 4.4,
      },
      {
        id: 'tr_005',
        title: 'Communication Excellence',
        description: 'Improve your communication skills for better stakeholder engagement.',
        type: 'case_study',
        category: 'communication',
        duration: 25,
        difficulty: 'intermediate',
        url: 'https://example.com/training/communication',
        tags: ['communication', 'skills', 'engagement'],
        completionRate: 0,
        rating: 4.7,
      },
    ];
  }),

  /**
   * Get coaching goals for an admin
   */
  getCoachingGoals: protectedProcedure.query(async ({ ctx }) => {
    return [
      {
        id: 'goal_001',
        adminId: ctx.user?.id,
        area: 'approval_speed',
        title: 'Reduce Approval Time to 7.5 Minutes',
        description: 'Decrease average approval time from 9.5 to 7.5 minutes',
        targetValue: 7.5,
        currentValue: 9.5,
        deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        priority: 'high',
        status: 'active',
        progress: 35,
        milestones: [
          {
            id: 'm_001',
            title: 'Reduce to 9 minutes',
            targetValue: 9,
            dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
            completed: true,
            completedDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
          },
          {
            id: 'm_002',
            title: 'Reduce to 8.5 minutes',
            targetValue: 8.5,
            dueDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
            completed: false,
          },
          {
            id: 'm_003',
            title: 'Reduce to 7.5 minutes',
            targetValue: 7.5,
            dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            completed: false,
          },
        ],
      },
      {
        id: 'goal_002',
        adminId: ctx.user?.id,
        area: 'accuracy',
        title: 'Reduce Error Rate to 0.8%',
        description: 'Decrease error rate from 2.1% to 0.8%',
        targetValue: 0.8,
        currentValue: 2.1,
        deadline: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000),
        priority: 'critical',
        status: 'active',
        progress: 20,
        milestones: [
          {
            id: 'm_004',
            title: 'Reduce to 1.8%',
            targetValue: 1.8,
            dueDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
            completed: false,
          },
          {
            id: 'm_005',
            title: 'Reduce to 1.2%',
            targetValue: 1.2,
            dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            completed: false,
          },
          {
            id: 'm_006',
            title: 'Reduce to 0.8%',
            targetValue: 0.8,
            dueDate: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000),
            completed: false,
          },
        ],
      },
    ];
  }),

  /**
   * Start a training course
   */
  startTraining: protectedProcedure
    .input(z.object({ trainingId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // Mock training start
      return {
        success: true,
        trainingId: input.trainingId,
        startedAt: new Date(),
        message: 'Training started successfully',
      };
    }),

  /**
   * Complete a training course
   */
  completeTraining: protectedProcedure
    .input(z.object({ trainingId: z.string(), rating: z.number().min(1).max(5) }))
    .mutation(async ({ ctx, input }) => {
      // Mock training completion
      return {
        success: true,
        trainingId: input.trainingId,
        completedAt: new Date(),
        rating: input.rating,
        message: 'Training completed successfully',
      };
    }),

  /**
   * Dismiss a recommendation
   */
  dismissRecommendation: protectedProcedure
    .input(z.object({ recommendationId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // Mock recommendation dismissal
      return {
        success: true,
        recommendationId: input.recommendationId,
        message: 'Recommendation dismissed',
      };
    }),

  /**
   * Accept a recommendation
   */
  acceptRecommendation: protectedProcedure
    .input(z.object({ recommendationId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // Mock recommendation acceptance
      return {
        success: true,
        recommendationId: input.recommendationId,
        message: 'Recommendation accepted',
      };
    }),

  /**
   * Get coaching insights and analytics
   */
  getCoachingInsights: protectedProcedure.query(async ({ ctx }) => {
    return [
      {
        id: 'insight_001',
        adminId: ctx.user?.id,
        date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
        type: 'strength',
        title: 'Strong Communication Skills',
        description: 'Your communication with team members is consistently positive and clear.',
        confidence: 92,
        actionable: false,
      },
      {
        id: 'insight_002',
        adminId: ctx.user?.id,
        date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        type: 'opportunity',
        title: 'Potential for Leadership Role',
        description: 'Based on your performance metrics, you\'re a strong candidate for team lead position.',
        confidence: 78,
        actionable: true,
        suggestedAction: 'Schedule meeting with manager to discuss career development',
      },
      {
        id: 'insight_003',
        adminId: ctx.user?.id,
        date: new Date(),
        type: 'trend',
        title: 'Improving Approval Speed',
        description: 'Your approval time has decreased by 8% over the last two weeks.',
        confidence: 85,
        actionable: false,
      },
    ];
  }),

  /**
   * Get coaching progress summary
   */
  getCoachingProgressSummary: protectedProcedure.query(async ({ ctx }) => {
    return {
      adminId: ctx.user?.id,
      overallProgress: 42,
      recommendationsProgress: 35,
      trainingProgress: 65,
      goalsProgress: 28,
      engagementScore: 78,
      nextMilestone: {
        title: 'Complete Time Management Training',
        dueDate: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000),
        estimatedImpact: 15,
      },
      recentAchievements: [
        {
          title: 'Completed Decision Making Framework Training',
          date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
          impact: 8,
        },
        {
          title: 'Reduced Approval Time by 5%',
          date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
          impact: 12,
        },
      ],
    };
  }),
});
