from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model
from .models import Follow
from .serializers import UserFollowSerializer

User = get_user_model()


def sync_counts(follower, following):
    """Sync follow counts for both users after follow/unfollow."""
    following.followers_count = Follow.objects.filter(following=following).count()
    following.save(update_fields=["followers_count"])
    follower.following_count = Follow.objects.filter(follower=follower).count()
    follower.save(update_fields=["following_count"])


def award_follow_points(following_user):
    try:
        from wallet.utils import award_points
        award_points(following_user, 5, "follower", "Gained a new follower")
    except Exception:
        pass


class FollowUser(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, user_id):
        follower = request.user
        try:
            following = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({"error": "User not found"}, status=404)

        if follower == following:
            return Response({"error": "You cannot follow yourself"}, status=400)

        follow, created = Follow.objects.get_or_create(
            follower=follower, following=following
        )
        if not created:
            return Response({"message": "Already following"}, status=200)

        sync_counts(follower, following)
        award_follow_points(following)
        return Response({"message": "Followed successfully"}, status=201)


class UnfollowUser(APIView):
    permission_classes = [IsAuthenticated]

    def delete(self, request, user_id):
        follower = request.user
        try:
            following = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({"error": "User not found"}, status=404)

        try:
            follow = Follow.objects.get(follower=follower, following=following)
            follow.delete()
        except Follow.DoesNotExist:
            return Response({"message": "You were not following this user"}, status=200)

        sync_counts(follower, following)
        return Response({"message": "Unfollowed successfully"}, status=200)


class CheckFollow(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, user_id):
        is_following = Follow.objects.filter(
            follower=request.user, following_id=user_id
        ).exists()
        return Response({"following": is_following})


class ListFollowers(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, user_id):
        follows = Follow.objects.filter(
            following_id=user_id
        ).select_related("follower")
        # Annotate live counts on each user object
        users = []
        for f in follows:
            u = f.follower
            u.followers_count = Follow.objects.filter(following=u).count()
            u.following_count = Follow.objects.filter(follower=u).count()
            users.append(u)
        serializer = UserFollowSerializer(users, many=True, context={"request": request})
        return Response(serializer.data)


class ListFollowing(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, user_id):
        follows = Follow.objects.filter(
            follower_id=user_id
        ).select_related("following")
        users = []
        for f in follows:
            u = f.following
            u.followers_count = Follow.objects.filter(following=u).count()
            u.following_count = Follow.objects.filter(follower=u).count()
            users.append(u)
        serializer = UserFollowSerializer(users, many=True, context={"request": request})
        return Response(serializer.data)


class SearchUsers(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        query = request.GET.get("q", "").strip()
        users = User.objects.exclude(id=request.user.id)
        if query:
            users = users.filter(username__icontains=query)
        # Annotate live counts
        result = []
        for u in users:
            u.followers_count = Follow.objects.filter(following=u).count()
            u.following_count = Follow.objects.filter(follower=u).count()
            result.append(u)
        serializer = UserFollowSerializer(result, many=True, context={"request": request})
        return Response(serializer.data)