from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from comments.models import Comment
from .serializers import CommentSerializer, CommentCreateSerializer
from likes.models import LikeComment

from posts.models import Post # Import Post model

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_comment(request):
    serializer = CommentCreateSerializer(data=request.data)
    if serializer.is_valid():
        # Get the post ID from the validated data
        post_id = serializer.validated_data.get('post').id if serializer.validated_data.get('post') else None
        if not post_id:
            return Response({'error': 'Post ID is required'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            post = Post.objects.get(id=post_id)
        except Post.DoesNotExist:
            return Response({'error': 'Post not found'}, status=status.HTTP_404_NOT_FOUND)

        # Vérifier si les commentaires sont autorisés pour ce post
        if not post.allow_comments:
            return Response({'error': 'Comments are not allowed for this post'}, status=status.HTTP_403_FORBIDDEN)

        comment = Comment.objects.create(
            created_by=request.user,
            **serializer.validated_data
        )

        # Create notification for post owner (don't notify self)
        if comment.post.created_by != request.user:
            from notifications.utils import create_notification
            create_notification(
                recipient=comment.post.created_by,
                sender=request.user,
                notification_type='comment',
                content=f'{request.user.first_name} {request.user.last_name} commented on your post',
                related_post=comment.post,
                related_comment=comment
            )

        return Response(CommentSerializer(comment, context={'request': request}).data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def list_comments(request, post_id):
    comments = Comment.objects.filter(post_id=post_id, is_active=True)

    if request.user.is_authenticated:
        from users.models import BlockedUser
        # Get IDs of blocked/blocking users
        blocked_ids = BlockedUser.objects.filter(blocker=request.user).values_list('blocked_id', flat=True)
        blocked_by_ids = BlockedUser.objects.filter(blocked=request.user).values_list('blocker_id', flat=True)

        comments = comments.exclude(created_by_id__in=blocked_ids).exclude(created_by_id__in=blocked_by_ids)


    # Pagination
    paginator = PageNumberPagination()
    paginator.page_size = 20
    result_page = paginator.paginate_queryset(comments, request)

    serializer = CommentSerializer(result_page, many=True, context={'request': request})
    return paginator.get_paginated_response(serializer.data)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_comment(request, comment_id):
    try:
        comment = Comment.objects.get(id=comment_id)

        # Vérifier que l'utilisateur est le créateur du commentaire
        if comment.created_by != request.user:
            return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        serializer = CommentCreateSerializer(comment, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(CommentSerializer(comment, context={'request': request}).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    except Comment.DoesNotExist:
        return Response({'error': 'Comment not found'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_comment(request, comment_id):
    try:
        comment = Comment.objects.get(id=comment_id)

        # Vérifier que l'utilisateur est le créateur du commentaire
        if comment.created_by != request.user:
            return Response({'error': 'Permission denied'}, status=status.HTTP_403_FORBIDDEN)

        # Soft delete
        comment.is_active = False
        comment.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
    except Comment.DoesNotExist:
        return Response({'error': 'Comment not found'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def like_comment(request, comment_id):
    try:
        comment = Comment.objects.get(id=comment_id, is_active=True)

        # Vérifier si l'utilisateur a déjà aimé ce commentaire
        if LikeComment.objects.filter(user=request.user, comment=comment).exists():
            return Response({'error': 'You already liked this comment'}, status=status.HTTP_400_BAD_REQUEST)

        LikeComment.objects.create(user=request.user, comment=comment)

        # Create notification for comment owner (don't notify self)
        if comment.created_by != request.user:
            from notifications.utils import create_notification
            create_notification(
                recipient=comment.created_by,
                sender=request.user,
                notification_type='like_comment',
                content=f'{request.user.first_name} {request.user.last_name} liked your comment',
                related_comment=comment,
                related_post=comment.post
            )

        return Response({'message': 'Comment liked successfully'}, status=status.HTTP_201_CREATED)
    except Comment.DoesNotExist:
        return Response({'error': 'Comment not found'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def unlike_comment(request, comment_id):
    try:
        comment = Comment.objects.get(id=comment_id, is_active=True)
        like = LikeComment.objects.filter(user=request.user, comment=comment)

        if not like.exists():
            return Response({'error': 'You don\'t like this comment'}, status=status.HTTP_400_BAD_REQUEST)

        like.delete()

        # Delete like notification
        from notifications.utils import delete_related_notifications
        delete_related_notifications(
            notification_type='like_comment',
            sender=request.user,
            recipient=comment.created_by,
            related_comment=comment
        )

        return Response({'message': 'Comment unliked successfully'}, status=status.HTTP_200_OK)
    except Comment.DoesNotExist:
        return Response({'error': 'Comment not found'}, status=status.HTTP_404_NOT_FOUND)