const CareerProgress = require('../models/CareerProgress');
const StudyGroup = require('../models/StudyGroup');
const Quiz = require('../models/Quiz');
const CareerPath = require('../models/CareerPath');
const User = require('../models/User');

// Get overall analytics dashboard
const getAnalyticsDashboard = async (req, res) => {
    try {
        const { timeframe = '30' } = req.query; // days
        const daysAgo = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);

        // Total users and active users
        const totalUsers = await User.countDocuments();
        const activeUsers = await CareerProgress.countDocuments({
            lastUpdated: { $gte: daysAgo }
        });

        // User distribution by stage
        const stageDistribution = await CareerProgress.aggregate([
            {
                $group: {
                    _id: '$currentStage',
                    count: { $sum: 1 }
                }
            },
            { $sort: { count: -1 } }
        ]);

        // Quiz statistics
        const quizStats = await CareerProgress.aggregate([
            {
                $group: {
                    _id: null,
                    totalAttempts: { $sum: '$quizStats.totalAttempts' },
                    totalCorrectAnswers: { $sum: '$quizStats.correctAnswers' },
                    avgScore: { $avg: '$quizStats.averageScore' }
                }
            }
        ]);

        // Study group statistics
        const studyGroupStats = await CareerProgress.aggregate([
            {
                $group: {
                    _id: null,
                    totalGroupsJoined: { $sum: '$studyGroupActivity.groupsJoined' },
                    totalPostsCreated: { $sum: '$studyGroupActivity.postsCreated' },
                    totalHelpfulAnswers: { $sum: '$studyGroupActivity.helpfulAnswers' }
                }
            }
        ]);

        // Achievement statistics
        const achievementStats = await CareerProgress.aggregate([
            { $unwind: '$achievements' },
            {
                $group: {
                    _id: '$achievements.type',
                    count: { $sum: 1 }
                }
            },
            { $sort: { count: -1 } }
        ]);

        // Streak statistics
        const streakStats = await CareerProgress.aggregate([
            {
                $group: {
                    _id: null,
                    avgCurrentStreak: { $avg: '$streak.current' },
                    avgLongestStreak: { $avg: '$streak.longest' },
                    maxStreak: { $max: '$streak.longest' }
                }
            }
        ]);

        // Top performing users
        const topUsers = await CareerProgress.aggregate([
            {
                $lookup: {
                    from: 'users',
                    localField: 'userId',
                    foreignField: '_id',
                    as: 'user'
                }
            },
            { $unwind: '$user' },
            {
                $project: {
                    name: '$user.name',
                    email: '$user.email',
                    currentStage: 1,
                    quizScore: '$quizStats.averageScore',
                    studyGroupActivity: 1,
                    streak: 1,
                    achievementsCount: { $size: '$achievements' }
                }
            },
            { $sort: { quizScore: -1, achievementsCount: -1 } },
            { $limit: 10 }
        ]);

        // Recent activity
        const recentActivity = await CareerProgress.find({
            lastUpdated: { $gte: daysAgo }
        })
        .populate('userId', 'name email')
        .select('userId currentStage lastUpdated quizStats.averageScore studyGroupActivity.groupsJoined')
        .sort({ lastUpdated: -1 })
        .limit(20);

        res.status(200).json({
            success: true,
            data: {
                overview: {
                    totalUsers,
                    activeUsers,
                    timeframe: `${timeframe} days`
                },
                stageDistribution,
                quizStats: quizStats[0] || { totalAttempts: 0, totalCorrectAnswers: 0, avgScore: 0 },
                studyGroupStats: studyGroupStats[0] || { totalGroupsJoined: 0, totalPostsCreated: 0, totalHelpfulAnswers: 0 },
                achievementStats,
                streakStats: streakStats[0] || { avgCurrentStreak: 0, avgLongestStreak: 0, maxStreak: 0 },
                topUsers,
                recentActivity
            }
        });
    } catch (error) {
        console.error('Get analytics dashboard error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get analytics dashboard',
            error: error.message
        });
    }
};

// Get detailed quiz analytics
const getQuizAnalytics = async (req, res) => {
    try {
        const { category, timeframe = '30' } = req.query;
        const daysAgo = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);

        // Category-wise performance
        const categoryPerformance = await CareerProgress.aggregate([
            { $unwind: '$quizStats.categoryScores' },
            ...(category ? [{ $match: { 'quizStats.categoryScores.category': category } }] : []),
            {
                $group: {
                    _id: '$quizStats.categoryScores.category',
                    avgScore: { $avg: '$quizStats.categoryScores.score' },
                    totalAttempts: { $sum: '$quizStats.categoryScores.attempts' },
                    usersCount: { $sum: 1 }
                }
            },
            { $sort: { avgScore: -1 } }
        ]);

        // Difficulty-wise performance
        const difficultyPerformance = await Quiz.aggregate([
            {
                $group: {
                    _id: '$difficulty',
                    totalQuestions: { $sum: 1 },
                    avgAttempts: { $avg: 1 }
                }
            }
        ]);

        // Top performing categories
        const topCategories = await CareerProgress.aggregate([
            { $unwind: '$quizStats.categoryScores' },
            {
                $group: {
                    _id: '$quizStats.categoryScores.category',
                    avgScore: { $avg: '$quizStats.categoryScores.score' },
                    totalAttempts: { $sum: '$quizStats.categoryScores.attempts' }
                }
            },
            { $sort: { avgScore: -1 } },
            { $limit: 10 }
        ]);

        res.status(200).json({
            success: true,
            data: {
                categoryPerformance,
                difficultyPerformance,
                topCategories,
                timeframe: `${timeframe} days`
            }
        });
    } catch (error) {
        console.error('Get quiz analytics error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get quiz analytics',
            error: error.message
        });
    }
};

// Get study group analytics
const getStudyGroupAnalytics = async (req, res) => {
    try {
        const { timeframe = '30' } = req.query;
        const daysAgo = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);

        // Study group statistics
        const totalGroups = await StudyGroup.countDocuments({ isActive: true });
        const totalMembers = await StudyGroup.aggregate([
            { $project: { memberCount: { $size: '$members' } } },
            { $group: { _id: null, total: { $sum: '$memberCount' } } }
        ]);

        // Most active study groups
        const activeGroups = await StudyGroup.aggregate([
            { $match: { isActive: true } },
            {
                $project: {
                    name: 1,
                    exam: 1,
                    stage: 1,
                    memberCount: { $size: '$members' },
                    createdAt: 1
                }
            },
            { $sort: { memberCount: -1 } },
            { $limit: 10 }
        ]);

        // User engagement in study groups
        const userEngagement = await CareerProgress.aggregate([
            {
                $group: {
                    _id: '$currentStage',
                    avgGroupsJoined: { $avg: '$studyGroupActivity.groupsJoined' },
                    avgPostsCreated: { $avg: '$studyGroupActivity.postsCreated' },
                    avgHelpfulAnswers: { $avg: '$studyGroupActivity.helpfulAnswers' },
                    usersCount: { $sum: 1 }
                }
            },
            { $sort: { avgGroupsJoined: -1 } }
        ]);

        res.status(200).json({
            success: true,
            data: {
                totalGroups,
                totalMembers: totalMembers[0]?.total || 0,
                activeGroups,
                userEngagement,
                timeframe: `${timeframe} days`
            }
        });
    } catch (error) {
        console.error('Get study group analytics error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get study group analytics',
            error: error.message
        });
    }
};

// Get user progress analytics
const getUserProgressAnalytics = async (req, res) => {
    try {
        const { stage, timeframe = '30' } = req.query;
        const daysAgo = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);

        const filter = { lastUpdated: { $gte: daysAgo } };
        if (stage) filter.currentStage = stage;

        // Goal completion statistics
        const goalStats = await CareerProgress.aggregate([
            { $match: filter },
            { $unwind: '$goals' },
            {
                $group: {
                    _id: '$currentStage',
                    avgProgress: { $avg: '$goals.progress' },
                    totalGoals: { $sum: 1 },
                    completedGoals: {
                        $sum: { $cond: [{ $eq: ['$goals.progress', 100] }, 1, 0] }
                    }
                }
            }
        ]);

        // Achievement distribution
        const achievementDistribution = await CareerProgress.aggregate([
            { $match: filter },
            { $unwind: '$achievements' },
            {
                $group: {
                    _id: '$achievements.type',
                    count: { $sum: 1 }
                }
            },
            { $sort: { count: -1 } }
        ]);

        // Streak analysis
        const streakAnalysis = await CareerProgress.aggregate([
            { $match: filter },
            {
                $group: {
                    _id: '$currentStage',
                    avgCurrentStreak: { $avg: '$streak.current' },
                    avgLongestStreak: { $avg: '$streak.longest' },
                    usersWithStreaks: {
                        $sum: { $cond: [{ $gt: ['$streak.current', 0] }, 1, 0] }
                    },
                    totalUsers: { $sum: 1 }
                }
            }
        ]);

        // Top performers by stage
        const topPerformers = await CareerProgress.aggregate([
            { $match: filter },
            {
                $lookup: {
                    from: 'users',
                    localField: 'userId',
                    foreignField: '_id',
                    as: 'user'
                }
            },
            { $unwind: '$user' },
            {
                $group: {
                    _id: '$currentStage',
                    topUsers: {
                        $push: {
                            name: '$user.name',
                            email: '$user.email',
                            quizScore: '$quizStats.averageScore',
                            achievementsCount: { $size: '$achievements' },
                            streak: '$streak.current'
                        }
                    }
                }
            },
            {
                $project: {
                    _id: 1,
                    topUsers: {
                        $slice: [
                            {
                                $sortArray: {
                                    input: '$topUsers',
                                    sortBy: { quizScore: -1, achievementsCount: -1 }
                                }
                            },
                            5
                        ]
                    }
                }
            }
        ]);

        res.status(200).json({
            success: true,
            data: {
                goalStats,
                achievementDistribution,
                streakAnalysis,
                topPerformers,
                timeframe: `${timeframe} days`
            }
        });
    } catch (error) {
        console.error('Get user progress analytics error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user progress analytics',
            error: error.message
        });
    }
};

module.exports = {
    getAnalyticsDashboard,
    getQuizAnalytics,
    getStudyGroupAnalytics,
    getUserProgressAnalytics
};
