from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Task, TaskComment, TimeLog
from .serializers import TaskSerializer, TaskCommentSerializer, TimeLogSerializer
from apps.users.views import api_response
from apps.notifications.views import create_notification


class TaskViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = TaskSerializer

    def get_queryset(self):
        user = self.request.user
        qs = Task.objects.all()
        project_id = self.request.query_params.get('project')
        if project_id:
            qs = qs.filter(project_id=project_id)
        
        # If not management, restrict to assigned tasks or tasks in their projects
        if not user.has_role('CEO', 'PM', 'TL'):
            from django.db.models import Q
            qs = qs.filter(Q(assigned_to=user) | Q(project__members__user=user)).distinct()
        return qs
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return api_response(data=serializer.data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return api_response(data=serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            return api_response(data=serializer.data, status_code=status.HTTP_201_CREATED)
        return api_response(errors=serializer.errors, status_code=status.HTTP_400_BAD_REQUEST)

    def perform_create(self, serializer):
        task = serializer.save(created_by=self.request.user)
        # Notify assignee if not the creator
        if task.assigned_to and task.assigned_to != self.request.user:
            create_notification(
                user=task.assigned_to,
                notif_type='task_assigned',
                title='New Task Assigned',
                message=f'{self.request.user.full_name} assigned a new task: {task.title}',
                link=f'/tasks'
            )

    @action(detail=True, methods=['post'])
    def log_time(self, request, pk=None):
        task = self.get_object()
        hours = request.data.get('hours')
        note = request.data.get('note', '')
        date = request.data.get('date')

        if not hours or not date:
            return api_response(message='Hours and date are required', status_code=status.HTTP_400_BAD_REQUEST)

        TimeLog.objects.create(
            task=task,
            user=request.user,
            hours=hours,
            date=date,
            note=note
        )
        return api_response(data=TaskSerializer(task).data, message='Time logged successfully')

    @action(detail=True, methods=['post'])
    def add_comment(self, request, pk=None):
        task = self.get_object()
        serializer = TaskCommentSerializer(data=request.data)
        if serializer.is_valid():
            comment = serializer.save(task=task, author=request.user)
            
            # Notify assignee or creator about the new comment
            recipients = set()
            if task.assigned_to: recipients.add(task.assigned_to)
            if task.created_by: recipients.add(task.created_by)
            # Don't notify the sender themselves
            recipients.discard(request.user)
            
            for recipient in recipients:
                create_notification(
                    user=recipient,
                    notif_type='comment',
                    title='New Task Comment',
                    message=f'{request.user.full_name} commented on task: {task.title}',
                    link=f'/tasks'
                )
            
            return api_response(data=TaskSerializer(task).data)
        return api_response(errors=serializer.errors, status_code=status.HTTP_400_BAD_REQUEST)

class TimeLogViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = TimeLogSerializer

    def get_queryset(self):
        qs = TimeLog.objects.all()
        task_id = self.request.query_params.get('task')
        user_id = self.request.query_params.get('user')
        if task_id:
            qs = qs.filter(task_id=task_id)
        if user_id:
            qs = qs.filter(user_id=user_id)
        return qs

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return api_response(data=serializer.data)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
