from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q
from django.conf import settings
from Auth.models import Profile, ProfileRole

import N3wtSchool.mailManager as mailer
from N3wtSchool import bdd
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.exceptions import NotFound
import uuid
import logging

# Ajouter un logger pour debug
logger = logging.getLogger(__name__)

class SendEmailView(APIView):
    """
    API pour envoyer des emails aux parents et professeurs.
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        # Ajouter du debug
        logger.info(f"Request data received (keys): {list(request.data.keys()) if request.data else []}")  # Ne pas logger les valeurs (RGPD)
        logger.info(f"Request content type: {request.content_type}")

        data = request.data
        recipients = data.get('recipients', [])
        cc = data.get('cc', [])
        bcc = data.get('bcc', [])
        subject = data.get('subject', 'Notification')
        message = data.get('message', '')
        establishment_id = data.get('establishment_id', '')

        # Debug des données reçues
        logger.info(f"Recipients (count): {len(recipients)}")
        logger.info(f"Subject: {subject}")
        logger.debug(f"Message length: {len(message) if message else 0}")
        logger.info(f"Establishment ID: {establishment_id}")

        if not recipients or not message:
            logger.error("Recipients or message missing")
            logger.error(f"Recipients empty: {not recipients}, Message empty: {not message}")
            logger.error(f"Recipients value: '{recipients}', Message value: '{message}'")
            return Response({'error': 'Les destinataires et le message sont requis.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # Récupérer la connexion SMTP
            logger.info("Tentative de récupération de la connexion SMTP...")
            connection = mailer.getConnection(establishment_id)
            logger.info(f"Connexion SMTP récupérée: {connection}")

            # Envoyer l'email
            logger.info("Tentative d'envoi de l'email...")
            result = mailer.sendMail(
                subject=subject,
                message=message,
                recipients=recipients,
                cc=cc,
                bcc=bcc,
                attachments=[],
                connection=connection
            )
            logger.info(f"Email envoyé avec succès: {result}")
            return result
        except NotFound as e:
            logger.error(f"NotFound error: {str(e)}")
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logger.error(f"Exception during email sending: {str(e)}", exc_info=True)
            return Response({'error': 'Erreur lors de l\'envoi de l\'email'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def search_recipients(request):
    """
    API pour rechercher des destinataires en fonction d'un terme de recherche et d'un établissement.
    """
    query = request.GET.get('q', '').strip()  # Récupérer le terme de recherche depuis les paramètres GET
    establishment_id = request.GET.get('establishment_id', None)  # Récupérer l'ID de l'établissement

    if not query:
        return JsonResponse([], safe=False)  # Retourner une liste vide si aucun terme n'est fourni

    if not establishment_id:
        return JsonResponse({'error': 'establishment_id est requis'}, safe=False, status=status.HTTP_400_BAD_REQUEST)

    # Rechercher dans les champs pertinents (nom, prénom, email) et filtrer par establishment_id
    profiles = Profile.objects.filter(
        Q(first_name__icontains=query) |
        Q(last_name__icontains=query) |
        Q(email__icontains=query),
        roles__establishment_id=establishment_id,  # Utiliser 'roles' au lieu de 'profilerole'
        roles__is_active=True  # Filtrer uniquement les ProfileRole actifs
    ).distinct()

    # Construire la réponse avec les rôles associés
    results = []
    for profile in profiles:
        profile_roles = ProfileRole.objects.filter(
            profile=profile,
            establishment_id=establishment_id,
            is_active=True  # Inclure uniquement les ProfileRole actifs
        ).values(
            'id', 'role_type', 'establishment__name', 'is_active'
        )
        results.append({
            'id': profile.id,
            'first_name': profile.first_name,
            'last_name': profile.last_name,
            'email': profile.email,
            'roles': list(profile_roles)  # Inclure tous les rôles actifs associés pour cet établissement
        })

    return JsonResponse(results, safe=False)


class SendFeedbackView(APIView):
    """
    API pour envoyer un feedback au support (EMAIL_HOST_USER).
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        data = request.data
        category = data.get('category', '')
        subject = data.get('subject', 'Feedback')
        message = data.get('message', '')
        user_email = data.get('user_email', '')
        user_name = data.get('user_name', '')
        establishment = data.get('establishment', {})

        logger.info(f"Feedback received - Category: {category}, Subject: {subject}")

        if not message or not subject or not category:
            return Response(
                {'error': 'La catégorie, le sujet et le message sont requis.'},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            # Construire le message formaté
            category_labels = {
                'bug': 'Signalement de bug',
                'feature': 'Proposition de fonctionnalité',
                'question': 'Question',
                'other': 'Autre'
            }
            category_label = category_labels.get(category, category)

            # Construire les infos établissement
            establishment_id = establishment.get('id', 'N/A')
            establishment_name = establishment.get('name', 'N/A')
            establishment_capacity = establishment.get('total_capacity', 'N/A')
            establishment_frequency = establishment.get('evaluation_frequency', 'N/A')

            formatted_message = f"""
            <h2>Nouveau Feedback - {category_label}</h2>
            <p><strong>De:</strong> {user_name} ({user_email})</p>
            <h3>Établissement</h3>
            <ul>
                <li><strong>ID:</strong> {establishment_id}</li>
                <li><strong>Nom:</strong> {establishment_name}</li>
                <li><strong>Capacité:</strong> {establishment_capacity}</li>
                <li><strong>Fréquence d'évaluation:</strong> {establishment_frequency}</li>
            </ul>
            <hr>
            <p><strong>Sujet:</strong> {subject}</p>
            <div>
                <strong>Message:</strong><br>
                {message}
            </div>
            """

            formatted_subject = f"[N3WT School Feedback] [{category_label}] {subject}"

            # Envoyer à EMAIL_HOST_USER avec la configuration SMTP par défaut
            result = mailer.sendMail(
                subject=formatted_subject,
                message=formatted_message,
                recipients=[settings.EMAIL_HOST_USER],
                cc=[],
                bcc=[],
                attachments=[],
                connection=None  # Utilise la configuration SMTP par défaut
            )

            logger.info("Feedback envoyé avec succès")
            return result

        except Exception as e:
            logger.error(f"Erreur lors de l'envoi du feedback: {str(e)}", exc_info=True)
            return Response(
                {'error': "Erreur lors de l'envoi du feedback"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
