from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from apps.notifications.models import Notification
from apps.dashboard.utils import get_user_info
from apps.notifications.forms import NotificationForm
from django.core.paginator import Paginator
from django.urls import reverse
from django.contrib.auth.models import User
from django.db import transaction
from apps.notifications.services import send_notification_to_all, send_notification_to_user, delete_sent_notification
from django.contrib.auth.decorators import login_required
from collections import defaultdict
from django.db.models import Q

def get_notifications(user):
    if user.is_authenticated:
        return Notification.objects.filter(user=user, is_read=False).order_by('-created_at')
    return Notification.objects.none()

@login_required
def create_notification(request):
    if request.method == 'POST':
        form = NotificationForm(request.POST)
        if form.is_valid():
            message = form.cleaned_data['message']
            notification_type = form.cleaned_data['notification_type']
            send_to_all = form.cleaned_data['send_to_all']
            choose_user = form.cleaned_data['choose_user']
            recipient = form.cleaned_data['recipient']

            try:
                with transaction.atomic():
                    if send_to_all:
                        send_notification_to_all(request.user, message, notification_type)
                    elif choose_user and recipient:
                        send_notification_to_user(request.user, recipient, message, notification_type)
                    else:
                        return JsonResponse({'success': False, 'errors': 'Selecione uma opção válida'}, status=400)

                return JsonResponse({'success': True, 'redirect_url': reverse('notification_list')})
            except Exception as e:
                return JsonResponse({'success': False, 'errors': str(e)}, status=500)
        return JsonResponse({'success': False, 'errors': form.errors}, status=400)
    return JsonResponse({'error': 'Invalid method'}, status=405)

@login_required
def delete_sent_notification_view(request, notification_id):
    if request.method == 'POST':
        success = delete_sent_notification(notification_id, request.user)
        if success:
            return JsonResponse({'success': True})
        return JsonResponse({'success': False, 'error': 'Notificação não encontrada ou não autorizada'}, status=404)
    return JsonResponse({'error': 'Método inválido'}, status=405)


def mark_as_read(request, notification_id):
    if request.user.is_authenticated:
        notification = get_object_or_404(Notification, id=notification_id, user=request.user)
        notification.is_read = True
        notification.save()
        return JsonResponse({'success': True})
    return JsonResponse({'error': 'Unauthorized'}, status=401)



def notification_list(request):
    if not request.user.is_authenticated:
        return redirect('index')

    query = request.GET.get('q', '')
    filter_type = request.GET.get('type', '')

    received_notifications = Notification.objects.filter(user=request.user).order_by('-created_at')
    sent_notifications = Notification.objects.filter(sender=request.user).order_by('-created_at')

    if query:
        received_notifications = received_notifications.filter(message__icontains=query)
        sent_notifications = sent_notifications.filter(message__icontains=query)

    if filter_type:
        received_notifications = received_notifications.filter(notification_type=filter_type)
        sent_notifications = sent_notifications.filter(notification_type=filter_type)

    paginator_received = Paginator(received_notifications, 10)  # 10 notificações por página
    paginator_sent = Paginator(sent_notifications, 10)  # 10 notificações por página

    page_number_received = request.GET.get('page_received')
    page_number_sent = request.GET.get('page_sent')

    page_obj_received = paginator_received.get_page(page_number_received)
    page_obj_sent = paginator_sent.get_page(page_number_sent)

    context = {
        'user_info': get_user_info(request.user.id),
        'page_obj_received': page_obj_received,
        'page_obj_sent': page_obj_sent,
        'query': query,
        'filter_type': filter_type,
        'notification_form': NotificationForm(),  # Passa o formulário para o contexto
    }
    return render(request, 'notifications/notification_list.html', context)

@login_required
def sent_notifications_list(request):
    if not request.user.is_authenticated:
        return redirect('index')

    query = request.GET.get('q', '')
    filter_type = request.GET.get('type', '')

    notification_list = Notification.objects.filter(sender=request.user).order_by('-created_at')

    if query:
        notification_list = notification_list.filter(message__icontains=query)

    if filter_type:
        notification_list = notification_list.filter(notification_type=filter_type)

    # Agrupar notificações enviadas para todos os usuários
    grouped_notifications = []
    seen_messages = set()

    for notification in notification_list:
        if notification.send_to_all:
            if notification.message not in seen_messages:
                grouped_notifications.append(notification)
                seen_messages.add(notification.message)
        else:
            grouped_notifications.append(notification)

    paginator = Paginator(grouped_notifications, 10)  # 10 notificações por página
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'user_info': get_user_info(request.user.id),
        'page_obj': page_obj,
        'query': query,
        'filter_type': filter_type,
    }
    return render(request, 'notifications/sent_notification_list.html', context)




def delete_notification(request, notification_id):
    if not request.user.is_authenticated:
        return redirect('index')
    notification = get_object_or_404(Notification, id=notification_id)
    if request.method == 'POST':
        notification.delete()
        return redirect('notification_list')
    
    context = {
        'user_info': get_user_info(request.user.id),
        'notification': notification,
    }
    return render(request, 'notifications/notification_list.html', context)
