from rest_framework import status, permissions
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from .models import Discussion, Message, MessageAttachment, MessageReaction
from .serializers import DiscussionSerializer, MessageSerializer, MessageReactionSerializer
from apps.users.views import api_response


class DiscussionView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        user = request.user
        lead_id = request.query_params.get('lead')
        project_id = request.query_params.get('project')
        task_id = request.query_params.get('task')

        # Mode A: Fetch or create specific board for a detail view (Lead/Project/Task Panel)
        if lead_id:
            discussion, _ = Discussion.objects.get_or_create(
                lead_id=lead_id, defaults={'board_type': 'lead'}
            )
            serializer = DiscussionSerializer(discussion)
            return api_response(data=serializer.data)
        elif project_id:
            discussion, _ = Discussion.objects.get_or_create(
                project_id=project_id, defaults={'board_type': 'project'}
            )
            serializer = DiscussionSerializer(discussion)
            return api_response(data=serializer.data)
        elif task_id:
            discussion, _ = Discussion.objects.get_or_create(
                task_id=task_id, defaults={'board_type': 'task'}
            )
            serializer = DiscussionSerializer(discussion)
            return api_response(data=serializer.data)

        # Mode B: List all boards (Directory View)
        # Managers see everything, members see assigned projects
        qs = Discussion.objects.all().order_by('-created_at')
        
        if not user.has_role('CEO', 'PM', 'TL'):
            from django.db.models import Q
            qs = qs.filter(
                Q(project__members__user=user) | 
                Q(lead__created_by=user)
            ).distinct()

        serializer = DiscussionSerializer(qs, many=True)
        return api_response(data=serializer.data)


class MessageListCreateView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, discussion_pk):
        try:
            discussion = Discussion.objects.get(pk=discussion_pk)
        except Discussion.DoesNotExist:
            return api_response(message='Discussion not found', status_code=status.HTTP_404_NOT_FOUND)

        messages = discussion.messages.filter(is_deleted=False, parent__isnull=True)
        serializer = MessageSerializer(messages, many=True)
        return api_response(data=serializer.data)

    def post(self, request, discussion_pk):
        try:
            discussion = Discussion.objects.get(pk=discussion_pk)
        except Discussion.DoesNotExist:
            return api_response(message='Discussion not found', status_code=status.HTTP_404_NOT_FOUND)

        content = request.data.get('content', '').strip()
        if not content:
            return api_response(message='Message content required', status_code=status.HTTP_400_BAD_REQUEST)

        message = Message.objects.create(
            discussion=discussion,
            author=request.user,
            content=content,
            parent_id=request.data.get('parent')
        )
        serializer = MessageSerializer(message)
        return api_response(
            data=serializer.data,
            message='Message sent',
            status_code=status.HTTP_201_CREATED
        )


class MessageDetailView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def patch(self, request, pk):
        try:
            message = Message.objects.get(pk=pk)
        except Message.DoesNotExist:
            return api_response(message='Message not found', status_code=status.HTTP_404_NOT_FOUND)

        # Only author can edit their own message
        if message.author != request.user:
            return api_response(message='Not authorized', status_code=status.HTTP_403_FORBIDDEN)

        if 'content' in request.data:
            message.content = request.data['content']
            message.save()

        return api_response(data=MessageSerializer(message).data, message='Message updated')

    def delete(self, request, pk):
        try:
            message = Message.objects.get(pk=pk)
        except Message.DoesNotExist:
            return api_response(message='Message not found', status_code=status.HTTP_404_NOT_FOUND)

        if message.author != request.user:
            return api_response(message='Not authorized', status_code=status.HTTP_403_FORBIDDEN)

        message.is_deleted = True
        message.save()
        return api_response(message='Message deleted')


class MessagePinView(APIView):
    """Pin/unpin messages — PM, TL, CEO only"""
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, pk):
        if not request.user.has_role('CEO', 'PM', 'TL'):
            return api_response(message='Not authorized to pin', status_code=status.HTTP_403_FORBIDDEN)

        try:
            message = Message.objects.get(pk=pk)
        except Message.DoesNotExist:
            return api_response(message='Message not found', status_code=status.HTTP_404_NOT_FOUND)

        message.is_pinned = not message.is_pinned
        message.save()
        action = 'pinned' if message.is_pinned else 'unpinned'
        return api_response(
            data=MessageSerializer(message).data,
            message=f'Message {action}'
        )


class MessageReactionView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, message_pk):
        try:
            message = Message.objects.get(pk=message_pk)
        except Message.DoesNotExist:
            return api_response(message='Message not found', status_code=status.HTTP_404_NOT_FOUND)

        emoji = request.data.get('emoji')
        if emoji not in ['👍', '✅', '❌', '🔥', '👀']:
            return api_response(message='Invalid emoji', status_code=status.HTTP_400_BAD_REQUEST)

        reaction, created = MessageReaction.objects.get_or_create(
            message=message, user=request.user, emoji=emoji
        )
        if not created:
            reaction.delete()
            return api_response(message='Reaction removed')

        return api_response(
            data=MessageReactionSerializer(reaction).data,
            message='Reaction added',
            status_code=status.HTTP_201_CREATED
        )


class MessageRepliesView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, message_pk):
        try:
            message = Message.objects.get(pk=message_pk)
        except Message.DoesNotExist:
            return api_response(message='Message not found', status_code=status.HTTP_404_NOT_FOUND)

        replies = message.replies.filter(is_deleted=False)
        serializer = MessageSerializer(replies, many=True)
        return api_response(data=serializer.data)
