from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import TimeSlot
from .serializers import TimeSlotSerializer
from permissions import DynamicModelPermission
from organization.mixins import TenantViewSetMixin

class TimeSlotViewSet(TenantViewSetMixin, viewsets.ModelViewSet):
    queryset = TimeSlot.objects.all()
    serializer_class = TimeSlotSerializer
    permission_classes = [IsAuthenticated, DynamicModelPermission]

    @action(detail=False, methods=['post'])
    def bulk_copy_global(self, request):
        slot_ids = request.data.get('slot_ids', [])
        if not slot_ids:
            return Response({"detail": "No slot IDs provided"}, status=status.HTTP_400_BAD_REQUEST)
        
        organization = getattr(request, 'organization', None)
        if not organization:
            return Response({"detail": "No organization found in request context. Please select an organization first."}, status=status.HTTP_400_BAD_REQUEST)

        global_slots = TimeSlot.objects.filter(id__in=slot_ids, is_global=True)
        if not global_slots.exists():
            return Response({"detail": "No global slots found with the provided IDs"}, status=status.HTTP_404_NOT_FOUND)
        copied_count = 0
        errors = []

        for slot in global_slots:
            # Check if an identical slot already exists for this organization to avoid duplicates
            if TimeSlot.objects.filter(
                organization=organization,
                start_time=slot.start_time,
                end_time=slot.end_time,
                is_global=False
            ).exists():
                errors.append(f"Slot {slot.slot_name} ({slot.start_time}-{slot.end_time}) already exists in your organization.")
                continue

            try:
                # Create a copy
                new_slot = TimeSlot(
                    organization=organization,
                    start_time=slot.start_time,
                    end_time=slot.end_time,
                    slot_name=slot.slot_name,
                    status=slot.status,
                    is_active=slot.is_active,
                    is_global=False
                )
                new_slot.save()
                copied_count += 1
            except Exception as e:
                errors.append(f"Error copying {slot.slot_name}: {str(e)}")

        return Response({
            "message": f"Successfully copied {copied_count} slots.",
            "copied_count": copied_count,
            "errors": errors
        }, status=status.HTTP_201_CREATED if copied_count > 0 else status.HTTP_200_OK)

    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        timeslot = self.get_object()
        
        # If is_active is not in request data, toggle it
        data = request.data.copy()
        if 'is_active' not in data:
            data['is_active'] = not timeslot.is_active
            
        serializer = self.get_serializer(timeslot, data=data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
