from flask import Blueprint, jsonify, request
from models.notification_model import Notification
from models.exam import Exam
from bson import ObjectId
from datetime import datetime, timezone

notification_bp = Blueprint('notification', __name__)

def time_ago(created_date):
    """Convert datetime to human-readable time ago format"""
    now = datetime.now(timezone.utc)
    # Make created_date offset-aware if it's naive
    if created_date.tzinfo is None or created_date.tzinfo.utcoffset(created_date) is None:
        created_date = created_date.replace(tzinfo=timezone.utc)
    diff = now - created_date

    seconds = diff.total_seconds()
    minutes = seconds // 60
    hours = minutes // 60
    days = diff.days

    if seconds < 60:
        return f"{int(seconds)} seconds ago"
    elif minutes < 60:
        return f"{int(minutes)} minutes ago"
    elif hours < 24:
        return f"{int(hours)} hours ago"
    else:
        return f"{int(days)} days ago"


@notification_bp.route("/get_notifications_list", methods=["GET"])
def get_active_notifications():
    try:
        # Get pagination params
        page = int(request.args.get("page", 1))
        limit = int(request.args.get("limit", 10))
        skip = (page - 1) * limit

        # Fetch only active notifications (status == 1), with pagination
        total_count = Notification.objects(status=1).count()
        notices = Notification.objects(status=1).order_by("-created_date").skip(skip).limit(limit)

        data = []
        for notice in notices:
            data.append({
                "id": str(notice.id),
                "title": notice.title,
                "description": notice.description,
                "is_read": notice.read,
                "image": notice.image if notice.image else None,
                "status": notice.status,
                "time_ago": time_ago(notice.created_date)
            })

        return jsonify({
            "status": True,
            "data": data,
            "page": page,
            "limit": limit,
            "total": total_count,
            "total_pages": (total_count + limit - 1) // limit
        }), 200

    except Exception as e:
        return jsonify({"status": False, "message": str(e)}), 500

@notification_bp.route("/mark_as_read_notification", methods=["POST"])
def mark_notification_as_read():
    try:
        notice_id = request.json.get("notification_id")
        if not notice_id or not ObjectId.is_valid(notice_id):
            return jsonify({"status": False, "message": "Invalid notification ID"}), 400

        notice = Notification.objects(id=ObjectId(notice_id)).first()
        if not notice:
            return jsonify({"status": False, "message": "Notification not found"}), 404

        notice.read = 1  # Mark as read
        notice.save()

        return jsonify({"status": True, "message": "Notification marked as read"}), 200

    except Exception as e:
        return jsonify({"status": False, "message": str(e)}), 500



# @job_notice_bp.route('/get_notices_list', methods=['GET'])
# def get_grouped_job_notices():
#     all_notices = JobNotice.objects.select_related()  # Prefetch exam data
#     grouped_data = {}

#     for notice in all_notices:
#         exam = notice.exam_id
#         exam_name = exam.exam_title if exam else "Unknown"

#         # Build notice data
#         notice_data = {
#             "title": notice.job_title,
#             "summary": notice.summary,
#             "notification_date": notice.notification_date.strftime('%Y-%m-%d') if notice.notification_date else None,
#             "application_start_date": notice.application_start_date.strftime('%Y-%m-%d') if notice.application_start_date else None,
#             "application_end_date": notice.application_end_date.strftime('%Y-%m-%d') if notice.application_end_date else None,
#             "exam_date": notice.exam_date.strftime('%Y-%m-%d') if notice.exam_date else None,
            
#         }

#         # Group by exam name
#         if exam_name not in grouped_data:
#             grouped_data[exam_name] = []
#         grouped_data[exam_name].append(notice_data)

#     return jsonify({"data": grouped_data, "status": True}), 200

# @job_notice_bp.route('/get_full_notice', methods=['POST'])
# def get_full_notice():
#     notice_id = request.json.get('notice_id')
#     if not notice_id:
#         return jsonify({"error": "Notice ID is required"}), 400
    
#     try:
#         notice = JobNotice.objects.get(id=ObjectId(notice_id))   
#         exam = notice.exam_id
#         exam_name = exam.exam_title if exam else "Unknown"
#         full_notice = {
#             "exam_name": exam_name,
#             "job_title": notice.job_title,
#             "full_content": notice.full_content,
#             "notification_date": notice.notification_date.strftime('%Y-%m-%d') if notice.notification_date else None,
#             "application_start_date": notice.application_start_date.strftime('%Y-%m-%d') if notice.application_start_date else None,
#             "application_end_date": notice.application_end_date.strftime('%Y-%m-%d') if notice.application_end_date else None,
#             "exam_date": notice.exam_date.strftime('%Y-%m-%d') if notice.exam_date else None,
#             "how_to_apply": notice.how_to_apply,
#             "is_urgent": notice.is_urgent
#         }
#         return jsonify({"data": full_notice, "status": True}), 200
#     except JobNotice.DoesNotExist:
#         return jsonify({"error": "Notice not found"}), 404

