from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from apps.users.permissions import IsManagement, IsOwnerOrManagement
from .models import Project, ProjectMember
from .serializers import (
    ProjectListSerializer, ProjectDetailSerializer, 
    ProjectMemberSerializer, ProjectCreateSerializer
)


from apps.users.views import api_response


class ProjectViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        qs = Project.objects.all()
        # If not management, maybe only see projects where they are members or PM
        if not user.has_role('CEO', 'PM', 'TL'):
            qs = qs.filter(members__user=user) | qs.filter(pm=user)
        return qs.distinct()

    def get_serializer_class(self):
        if self.action == 'list':
            return ProjectListSerializer
        if self.action == 'create':
            return ProjectCreateSerializer
        return ProjectDetailSerializer

    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 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,
                message='Project initialized',
                status_code=status.HTTP_201_CREATED
            )
        return api_response(
            errors=serializer.errors,
            message='Failed to initialize project',
            status_code=status.HTTP_400_BAD_REQUEST
        )

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

    @action(detail=True, methods=['post'], permission_classes=[IsManagement])
    def update_stage(self, request, pk=None):
        project = self.get_object()
        new_stage = request.data.get('stage')
        note = request.data.get('note', '')
        
        if new_stage not in dict(project.STAGE_CHOICES):
            return api_response(message='Invalid stage', status_code=status.HTTP_400_BAD_REQUEST)
        
        from_stage = project.stage
        project.stage = new_stage
        
        # If moving to 'Completed', maybe also update status
        if new_stage == 'Completed':
            project.status = 'Completed'
        
        project.save()
        
        # Log the change
        from .models import ProjectStageLog
        ProjectStageLog.objects.create(
            project=project,
            from_stage=from_stage,
            to_stage=new_stage,
            note=note,
            changed_by=request.user
        )
        
        return api_response(
            data=ProjectDetailSerializer(project).data,
            message=f'Project moved to {new_stage}'
        )

    @action(detail=True, methods=['post'], permission_classes=[IsManagement])
    def add_member(self, request, pk=None):
        project = self.get_object()
        user_id = request.data.get('user')
        role = request.data.get('role_on_project', 'Team Member')
        
        if not user_id:
            return Response({'error': 'User ID required'}, status=status.HTTP_400_BAD_REQUEST)
        
        # We would probably set hourly_rate_snapshot here from User model
        from apps.users.models import CustomUser
        try:
            member_user = CustomUser.objects.get(id=user_id)
            member, created = ProjectMember.objects.get_or_create(
                project=project,
                user=member_user,
                defaults={'role_on_project': role, 'hourly_rate_snapshot': member_user.hourly_rate}
            )
            return Response(ProjectDetailSerializer(project).data)
        except CustomUser.DoesNotExist:
            return Response({'error': 'User not found'}, status=status.HTTP_404_NOT_FOUND)

    @action(detail=True, methods=['post'], url_path='remove_member/(?P<member_id>[^/.]+)', permission_classes=[IsManagement])
    def remove_member(self, request, member_id=None, pk=None):
        project = self.get_object()
        try:
            member = ProjectMember.objects.get(id=member_id, project=project)
            member.delete()
            return Response(ProjectDetailSerializer(project).data)
        except ProjectMember.DoesNotExist:
            return Response({'error': 'Member not found'}, status=status.HTTP_404_NOT_FOUND)
