import logging
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework import viewsets, status
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend

from apps.calls.constants import BotType
from apps.appointments.models import Appointment
from apps.appointments.filters import AppointmentFilter
from apps.appointments.services import AppointmentService
from apps.appointments.pagination import AppointmentLimitOffsetPagination
from apps.appointments.serializers import (
    AppointmentSerializer,
    BookAppointmentInputSerializer,
    WebhookSuccessSerializer
)


logger = logging.getLogger(__name__)


class AppointmentViewSet(viewsets.ModelViewSet):
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = AppointmentLimitOffsetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = AppointmentFilter
    search_fields = ["name", "twilio_call_sid", "call__from_number"]
    ordering_fields = ["scheduled_date", "appointment_phone", "created_at", "name"]
    ordering = ["-created_at"]

    def get_queryset(self):
        user = self.request.user

        if user.is_superuser:
            return self.queryset.order_by("-scheduled_date")

        if getattr(user, "active_company", None):
            try:
                return (
                    self.queryset
                    .filter(company=user.active_company, bot_type=BotType.SALES_BOT.value)
                    .order_by("-scheduled_date")
                )
            except Exception:
                return self.queryset.none()

        return self.queryset.none()

    ## ========================= WEB HOOKS ===========================
    @action(
        detail=False,
        methods=["post"],
        url_path="book-appointment",
        permission_classes=[AllowAny],
        authentication_classes=[],
    )
    def book_appointment(self, request):
        """
        Endpoint for sales bot webhook.
        """
        serializer = BookAppointmentInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            AppointmentService.book_sales_bot_appointment(serializer.validated_data)
        except Exception as exc:
            logger.exception("Failed booking sales appointment: %s", exc)
            return Response({"message": "Failed to book appointment"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response(WebhookSuccessSerializer({"message": "Appointment booked successfully"}).data, status=status.HTTP_200_OK)

    @action(
        detail=False,
        methods=["post"],
        url_path="book-service-appointment",
        permission_classes=[AllowAny],
        authentication_classes=[],
    )
    def book_service_appointment(self, request):
        """
        Endpoint for service bot webhook.
        """
        serializer = BookAppointmentInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            AppointmentService.book_service_bot_appointment(serializer.validated_data)
        except Exception as exc:
            logger.exception("Failed booking service appointment: %s", exc)
            return Response({"message": "Failed to book appointment"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response(WebhookSuccessSerializer({"message": "Appointment booked successfully"}).data, status=status.HTTP_200_OK)
