import time
from django.utils.timezone import now 
from rest_framework.response import Response
from rest_framework import status
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.conf import settings
from vendor_listing.celery import app
import logging
from firebase_admin import messaging
from notification.firebase import firebase_app 
from .models import *
from order.models import OrderItem

logger = logging.getLogger(__name__)



@app.task(name='send_push_notification_task')
def send_push_notification_task(fcm_token, title, message):
    try:
        msg = messaging.Message(
            notification=messaging.Notification(title=title, body=message),
            token=fcm_token
        )
        response = messaging.send(msg)
        logger.info(f"Push notification sent to {fcm_token}: {response}")
        return f"Success: {response}"
    except Exception as e:
        logger.error(f"Push notification failed for {fcm_token}: {str(e)}")
        return f"Error: {str(e)}"
    

@app.task(name='send_admin_notification_to_buyers')
def send_admin_notification_to_buyers(notification_id):
    try:
        notification = Notification.objects.get(id=notification_id)
    except Notification.DoesNotExist:
        error_msg = f"Notification ID {notification_id} not found."
        logger.error(error_msg)
        return error_msg

    active_devices = Device.objects.filter(status=True)
    logger.info(f"Sending notification '{notification.title}' to {active_devices.count()} active buyer devices.")

    history_entries = []

    title = notification.title
    message = notification.description

    for device in active_devices:
        # Send push notification asynchronously
        send_push_notification_task.delay(
            fcm_token=device.device_id,
            title=title,
            message=message
        )

        # Prepare notification history record
        history_entries.append(NotificationHistory(
            notification=notification,
            device=device,
            # title=title,
            # message=message,
            sent_at=now()
        ))

    NotificationHistory.objects.bulk_create(history_entries)
    logger.info(f"Notification history created for {len(history_entries)} devices (Notification ID: {notification_id})")

    return f"Queued push notifications for {len(history_entries)} buyer devices."


@app.task(name='create_vendor_order_notification')
def create_vendor_order_notification(order_item_id):
    try:
        order_item = OrderItem.objects.select_related('vendor', 'order_purchase').get(id=order_item_id)

        message = f"New order received for {order_item.product.title} - Order #{order_item.order_purchase.id}"
        title = "New Order Received"

        NotificationHistory.objects.create(
            vendor=order_item.vendor,
            title=title,
            message=message,
            is_read=False,
            sent_at=now()
        )

        return f"Vendor notification created for order_item ID {order_item_id}"

    except Exception as e:
        logger.info(f"Failed to create vendor notification for order_item {order_item_id}: {str(e)}")
        return f"Error creating vendor notification for order_item {order_item_id}"
    

@app.task(name='create_user_notification')
def create_user_notification(user_type, user_id, title, message, order_id=None, order_item_id=None):
    try:
        logger.info(f"📨 Sending notification to {user_type} ID {user_id} with title: {title}")
    
        if user_type == 'buyer':
            device = Device.objects.filter(device_id=user_id, status=True).first()
            if not device:
                logger.warning(f"Device not found or inactive for buyer device_id={user_id}")
                return "Buyer device not found."

            NotificationHistory.objects.create(
                device=device,
                title=title,
                message=message,
                sent_at=now(),
                is_read=False
            )

            try:
                send_push_notification_task.delay(
                    fcm_token=device.device_id,
                    title=title,
                    message=message
                )
                logger.info(f"Push notification sent to buyer device {device.device_id}")
            except Exception as push_error:
                logger.exception(f"Failed to enqueue push for buyer device_id={user_id}: {str(push_error)}")

        elif user_type == 'vendor':
            
            vendor = User.objects.filter(id=user_id, is_active=True).first()
            if not vendor:
                logger.warning(f"Vendor not found or inactive: user_id={user_id}")
                return "Vendor not found."

            NotificationHistory.objects.create(
                vendor=vendor,
                title=title,
                message=message,
                sent_at=now(),
                is_read=False
            )

        else:
            logger.error(f"Invalid user_type passed: {user_type}")
            return "Invalid user_type."

        logger.info(f"{user_type.capitalize()} notification created for ID {user_id}")
        return f"{user_type.capitalize()} notification created."

    except Exception as e:
        logger.exception(f"Error creating notification for {user_type} ID={user_id}: {str(e)}")
        return f"Failed to create notification for {user_type} ID={user_id}"


@app.task(name='notify_vendor_payout_status')
def notify_vendor_payout_status(vendor, payout_amount, approved=True, reason=None):
    """
    Sends a notification to the vendor regarding their payout request.
    """
    try:
        title = "Payout Approved" if approved else "Payout Rejected"

        if approved:
            message = f"Your payout request of TZS {payout_amount} has been approved and processed."
        else:
            message = f"Your payout request of TZS {payout_amount} was rejected."
            if reason:
                message += f" Reason: {reason}"

        # Send notification via Celery
        create_user_notification.delay(
            user_type='vendor',
            user_id=vendor,
            title=title,
            message=message
        )

        logger.info(f"[PAYOUT NOTIFICATION] Vendor ID {vendor} - {title} - TZS {payout_amount}")

    except Exception as e:
        logger.exception(f"Failed to send payout notification to vendor ID {vendor}: {str(e)}")