const TherapistProfile = require("../../models/TherapistProfile");
const User = require("../../models/userModel");
const mongoose = require("mongoose");

// Get all therapist profiles pending approval
const getPendingApprovals = async (req, res) => {
  try {
    const { page = 1, limit = 10, status = 'pending' } = req.query;
    
    const validStatuses = ['pending', 'approved', 'rejected', 'changes_requested'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: "Invalid status. Must be one of: pending, approved, rejected, changes_requested"
      });
    }

    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    const profiles = await TherapistProfile.find({ approvalStatus: status })
      .populate('user', 'fullname email mobile createdAt')
      .sort({ updatedAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    const total = await TherapistProfile.countDocuments({ approvalStatus: status });

    return res.status(200).json({
      success: true,
      message: `Therapist profiles with ${status} status fetched successfully`,
      data: {
        profiles,
        pagination: {
          currentPage: parseInt(page),
          totalPages: Math.ceil(total / parseInt(limit)),
          totalItems: total,
          itemsPerPage: parseInt(limit)
        }
      }
    });

  } catch (error) {
    console.error("Get pending approvals error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Get specific therapist profile for review
const getTherapistProfileForReview = async (req, res) => {
  try {
    const { therapistId } = req.params;

    if (!mongoose.Types.ObjectId.isValid(therapistId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid therapist ID"
      });
    }

    const profile = await TherapistProfile.findOne({ user: therapistId })
      .populate('user', 'fullname email mobile gender createdAt')
      .populate('approvalHistory.adminId', 'fullname email');

    if (!profile) {
      return res.status(404).json({
        success: false,
        message: "Therapist profile not found"
      });
    }

    // Get therapist's appointment statistics
    const Appointment = require("../../models/Appointment");
    const appointmentStats = await Appointment.aggregate([
      { $match: { doctor: new mongoose.Types.ObjectId(therapistId) } },
      {
        $group: {
          _id: '$status',
          count: { $sum: 1 }
        }
      }
    ]);

    const stats = {
      total: 0,
      completed: 0,
      scheduled: 0,
      cancelled: 0
    };

    appointmentStats.forEach(stat => {
      stats.total += stat.count;
      stats[stat._id] = stat.count;
    });

    return res.status(200).json({
      success: true,
      message: "Therapist profile fetched successfully",
      data: {
        profile,
        appointmentStats: stats
      }
    });

  } catch (error) {
    console.error("Get therapist profile for review error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Approve therapist profile changes
const approveTherapistProfile = async (req, res) => {
  try {
    const adminId = req.user.id;
    const { therapistId } = req.params;
    const { reason } = req.body;

    if (!mongoose.Types.ObjectId.isValid(therapistId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid therapist ID"
      });
    }

    const profile = await TherapistProfile.findOne({ user: therapistId });

    if (!profile) {
      return res.status(404).json({
        success: false,
        message: "Therapist profile not found"
      });
    }

    // Update approval status
    profile.approvalStatus = 'approved';
    profile.approvalHistory.push({
      status: 'approved',
      adminId: adminId,
      reason: reason || 'Profile approved by admin',
      changedAt: new Date()
    });

    await profile.save();

    // Send notification to therapist (you can implement email/SMS notification here)
    // await sendNotificationToTherapist(therapistId, 'approved', reason);

    return res.status(200).json({
      success: true,
      message: "Therapist profile approved successfully",
      data: profile
    });

  } catch (error) {
    console.error("Approve therapist profile error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Reject therapist profile changes
const rejectTherapistProfile = async (req, res) => {
  try {
    const adminId = req.user.id;
    const { therapistId } = req.params;
    const { reason } = req.body;

    if (!reason || reason.trim().length === 0) {
      return res.status(400).json({
        success: false,
        message: "Reason for rejection is required"
      });
    }

    if (!mongoose.Types.ObjectId.isValid(therapistId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid therapist ID"
      });
    }

    const profile = await TherapistProfile.findOne({ user: therapistId });

    if (!profile) {
      return res.status(404).json({
        success: false,
        message: "Therapist profile not found"
      });
    }

    // Update approval status
    profile.approvalStatus = 'rejected';
    profile.approvalHistory.push({
      status: 'rejected',
      adminId: adminId,
      reason: reason,
      changedAt: new Date()
    });

    await profile.save();

    // Send notification to therapist
    // await sendNotificationToTherapist(therapistId, 'rejected', reason);

    return res.status(200).json({
      success: true,
      message: "Therapist profile rejected successfully",
      data: profile
    });

  } catch (error) {
    console.error("Reject therapist profile error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Request changes to therapist profile
const requestChanges = async (req, res) => {
  try {
    const adminId = req.user.id;
    const { therapistId } = req.params;
    const { reason, requestedChanges } = req.body;

    if (!reason || reason.trim().length === 0) {
      return res.status(400).json({
        success: false,
        message: "Reason for requesting changes is required"
      });
    }

    if (!mongoose.Types.ObjectId.isValid(therapistId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid therapist ID"
      });
    }

    const profile = await TherapistProfile.findOne({ user: therapistId });

    if (!profile) {
      return res.status(404).json({
        success: false,
        message: "Therapist profile not found"
      });
    }

    // Update approval status
    profile.approvalStatus = 'changes_requested';
    profile.approvalHistory.push({
      status: 'changes_requested',
      adminId: adminId,
      reason: reason,
      changes: requestedChanges || {},
      changedAt: new Date()
    });

    await profile.save();

    // Send notification to therapist
    // await sendNotificationToTherapist(therapistId, 'changes_requested', reason);

    return res.status(200).json({
      success: true,
      message: "Changes requested successfully",
      data: profile
    });

  } catch (error) {
    console.error("Request changes error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Get approval statistics
const getApprovalStatistics = async (req, res) => {
  try {
    const stats = await TherapistProfile.aggregate([
      {
        $group: {
          _id: '$approvalStatus',
          count: { $sum: 1 }
        }
      }
    ]);

    const statistics = {
      total: 0,
      pending: 0,
      approved: 0,
      rejected: 0,
      changes_requested: 0
    };

    stats.forEach(stat => {
      statistics.total += stat.count;
      statistics[stat._id] = stat.count;
    });

    // Get recent activity (last 30 days)
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const recentActivity = await TherapistProfile.find({
      'approvalHistory.changedAt': { $gte: thirtyDaysAgo }
    })
    .populate('user', 'fullname')
    .populate('approvalHistory.adminId', 'fullname')
    .sort({ 'approvalHistory.changedAt': -1 })
    .limit(10);

    return res.status(200).json({
      success: true,
      message: "Approval statistics fetched successfully",
      data: {
        statistics,
        recentActivity: recentActivity.map(profile => ({
          therapistId: profile.user._id,
          therapistName: profile.user.fullname,
          currentStatus: profile.approvalStatus,
          lastActivity: profile.approvalHistory[profile.approvalHistory.length - 1]
        }))
      }
    });

  } catch (error) {
    console.error("Get approval statistics error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Bulk approve multiple therapist profiles
const bulkApproveProfiles = async (req, res) => {
  try {
    const adminId = req.user.id;
    const { therapistIds, reason } = req.body;

    if (!Array.isArray(therapistIds) || therapistIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: "Array of therapist IDs is required"
      });
    }

    // Validate all IDs
    const invalidIds = therapistIds.filter(id => !mongoose.Types.ObjectId.isValid(id));
    if (invalidIds.length > 0) {
      return res.status(400).json({
        success: false,
        message: `Invalid therapist IDs: ${invalidIds.join(', ')}`
      });
    }

    const updateResult = await TherapistProfile.updateMany(
      { 
        user: { $in: therapistIds },
        approvalStatus: 'pending'
      },
      {
        $set: { approvalStatus: 'approved' },
        $push: {
          approvalHistory: {
            status: 'approved',
            adminId: adminId,
            reason: reason || 'Bulk approval by admin',
            changedAt: new Date()
          }
        }
      }
    );

    return res.status(200).json({
      success: true,
      message: `${updateResult.modifiedCount} therapist profiles approved successfully`,
      data: {
        approvedCount: updateResult.modifiedCount,
        totalRequested: therapistIds.length
      }
    });

  } catch (error) {
    console.error("Bulk approve profiles error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

// Deactivate therapist profile
const deactivateTherapistProfile = async (req, res) => {
  try {
    const adminId = req.user.id;
    const { therapistId } = req.params;
    const { reason } = req.body;

    if (!mongoose.Types.ObjectId.isValid(therapistId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid therapist ID"
      });
    }

    const profile = await TherapistProfile.findOne({ user: therapistId });

    if (!profile) {
      return res.status(404).json({
        success: false,
        message: "Therapist profile not found"
      });
    }

    // Deactivate profile
    profile.isActive = false;
    profile.approvalHistory.push({
      status: 'deactivated',
      adminId: adminId,
      reason: reason || 'Profile deactivated by admin',
      changedAt: new Date()
    });

    await profile.save();

    // Cancel all future appointments
    const Appointment = require("../../models/Appointment");
    await Appointment.updateMany(
      {
        doctor: therapistId,
        date: { $gt: new Date() },
        status: 'scheduled'
      },
      {
        $set: { status: 'cancelled' }
      }
    );

    return res.status(200).json({
      success: true,
      message: "Therapist profile deactivated successfully",
      data: profile
    });

  } catch (error) {
    console.error("Deactivate therapist profile error:", error);
    return res.status(500).json({
      success: false,
      message: "Server Error",
      error: error.message
    });
  }
};

module.exports = {
  getPendingApprovals,
  getTherapistProfileForReview,
  approveTherapistProfile,
  rejectTherapistProfile,
  requestChanges,
  getApprovalStatistics,
  bulkApproveProfiles,
  deactivateTherapistProfile
};
