const express = require('express');
const Patient = require('../models/Patient');
const Doctor = require('../models/Doctor');
const Appointment = require('../models/Appointment');
const { protect } = require('../middleware/auth');

const router = express.Router();

// @route   GET /api/reports/overview
// @desc    Get dashboard overview statistics
// @access  Private
router.get('/overview', protect, async (req, res) => {
  try {
    const totalPatients = await Patient.countDocuments();
    const totalDoctors = await Doctor.countDocuments();
    const totalAppointments = await Appointment.countDocuments();
    
    const scheduledAppointments = await Appointment.countDocuments({ status: 'scheduled' });
    const completedAppointments = await Appointment.countDocuments({ status: 'completed' });
    const cancelledAppointments = await Appointment.countDocuments({ status: 'cancelled' });

    // Get recent appointments
    const recentAppointments = await Appointment.find()
      .populate('patient', 'name')
      .populate('doctor', 'name')
      .sort({ createdAt: -1 })
      .limit(5);

    res.json({
      totalPatients,
      totalDoctors,
      totalAppointments,
      scheduledAppointments,
      completedAppointments,
      cancelledAppointments,
      recentAppointments
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   GET /api/reports/patients
// @desc    Get patient reports
// @access  Private
router.get('/patients', protect, async (req, res) => {
  try {
    const totalPatients = await Patient.countDocuments();
    
    // Patients added this month
    const startOfMonth = new Date();
    startOfMonth.setDate(1);
    startOfMonth.setHours(0, 0, 0, 0);
    
    const newPatientsThisMonth = await Patient.countDocuments({
      createdAt: { $gte: startOfMonth }
    });

    // Gender distribution
    const malePatients = await Patient.countDocuments({ gender: 'Male' });
    const femalePatients = await Patient.countDocuments({ gender: 'Female' });
    const otherPatients = await Patient.countDocuments({ gender: 'Other' });

    // Blood group distribution
    const bloodGroupStats = await Patient.aggregate([
      {
        $group: {
          _id: '$bloodGroup',
          count: { $sum: 1 }
        }
      }
    ]);

    // Age distribution
    const ageGroups = await Patient.aggregate([
      {
        $bucket: {
          groupBy: '$age',
          boundaries: [0, 18, 30, 50, 70, 150],
          default: 'Other',
          output: { count: { $sum: 1 } }
        }
      }
    ]);

    res.json({
      totalPatients,
      newPatientsThisMonth,
      genderDistribution: {
        male: malePatients,
        female: femalePatients,
        other: otherPatients
      },
      bloodGroupStats,
      ageGroups
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   GET /api/reports/doctors
// @desc    Get doctor reports
// @access  Private
router.get('/doctors', protect, async (req, res) => {
  try {
    const totalDoctors = await Doctor.countDocuments();

    // Specialty distribution
    const specialtyStats = await Doctor.aggregate([
      {
        $group: {
          _id: '$specialty',
          count: { $sum: 1 }
        }
      },
      {
        $sort: { count: -1 }
      }
    ]);

    // Department distribution
    const departmentStats = await Doctor.aggregate([
      {
        $group: {
          _id: '$department',
          count: { $sum: 1 }
        }
      },
      {
        $sort: { count: -1 }
      }
    ]);

    // Experience distribution
    const experienceStats = await Doctor.aggregate([
      {
        $bucket: {
          groupBy: '$experience',
          boundaries: [0, 5, 10, 15, 20, 50],
          default: 'Other',
          output: { count: { $sum: 1 } }
        }
      }
    ]);

    // Average experience
    const avgExperience = await Doctor.aggregate([
      {
        $group: {
          _id: null,
          avgExperience: { $avg: '$experience' }
        }
      }
    ]);

    res.json({
      totalDoctors,
      specialtyStats,
      departmentStats,
      experienceStats,
      avgExperience: avgExperience[0]?.avgExperience || 0
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   GET /api/reports/appointments
// @desc    Get appointment reports
// @access  Private
router.get('/appointments', protect, async (req, res) => {
  try {
    const totalAppointments = await Appointment.countDocuments();

    const scheduledAppointments = await Appointment.countDocuments({ status: 'scheduled' });
    const completedAppointments = await Appointment.countDocuments({ status: 'completed' });
    const cancelledAppointments = await Appointment.countDocuments({ status: 'cancelled' });

    // Appointments by status
    const statusDistribution = {
      scheduled: scheduledAppointments,
      completed: completedAppointments,
      cancelled: cancelledAppointments
    };

    // Appointments this month
    const startOfMonth = new Date();
    startOfMonth.setDate(1);
    startOfMonth.setHours(0, 0, 0, 0);

    const appointmentsThisMonth = await Appointment.countDocuments({
      createdAt: { $gte: startOfMonth }
    });

    // Daily appointments for the last 7 days
    const last7Days = [];
    for (let i = 6; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      date.setHours(0, 0, 0, 0);
      
      const nextDate = new Date(date);
      nextDate.setDate(nextDate.getDate() + 1);

      const count = await Appointment.countDocuments({
        date: { $gte: date, $lt: nextDate }
      });

      last7Days.push({
        date: date.toISOString().split('T')[0],
        count
      });
    }

    // Top doctors by appointments
    const topDoctors = await Appointment.aggregate([
      {
        $group: {
          _id: '$doctor',
          count: { $sum: 1 }
        }
      },
      {
        $sort: { count: -1 }
      },
      {
        $limit: 5
      },
      {
        $lookup: {
          from: 'doctors',
          localField: '_id',
          foreignField: '_id',
          as: 'doctor'
        }
      },
      {
        $unwind: '$doctor'
      },
      {
        $project: {
          name: '$doctor.name',
          specialty: '$doctor.specialty',
          count: 1
        }
      }
    ]);

    res.json({
      totalAppointments,
      statusDistribution,
      appointmentsThisMonth,
      last7Days,
      topDoctors
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;
