from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# from rest_framework.pagination import PageNumberPagination
from common.pagination.custom_pagination import CustomPageNumberPagination
from rest_framework.exceptions import ValidationError, NotFound
from drf_yasg.utils import swagger_auto_schema
from django.shortcuts import get_object_or_404

from api.property_api.country.models.country import Country
from api.property_api.country.serializers.country_serializer import CountrySerializer, CountryDropdownSerializer


class CountryListCreateAPIView(APIView):
    @swagger_auto_schema(request_body=CountrySerializer)
    def post(self, request):
        serializer = CountrySerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"success": "Country created successfully"}, status=status.HTTP_201_CREATED)

    def get(self, request):
        # countries = Country.objects.filter(is_active=True)
        search = request.query_params.get('search')
        countries = Country.objects.all()
        if search:
            countries = Country.objects.filter(name__icontains=search)
        paginator = CustomPageNumberPagination()
        result_page = paginator.paginate_queryset(countries, request)
        serializer = CountrySerializer(result_page, many=True)
        return paginator.get_paginated_response(serializer.data)


class CountryDetailAPIView(APIView):
    @swagger_auto_schema(request_body=CountrySerializer)
    def put(self, request, pk):
        country = get_object_or_404(Country, pk=pk)
        serializer = CountrySerializer(country, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"success": "Country updated successfully"}, status=status.HTTP_200_OK)

    def get(self, request, pk):
        country = get_object_or_404(Country, pk=pk)
        serializer = CountrySerializer(country)
        return Response(serializer.data)

    def delete(self, request, pk):
        country = get_object_or_404(Country, pk=pk)
        country.delete()
        return Response({"success": "Country deleted successfully"}, status=status.HTTP_200_OK)


class CountryDropdownAPIView(APIView):
    def get(self, request):
        countries = Country.objects.all()
        if not countries.exists():
            raise NotFound("No active countries found.")

        serializer = CountryDropdownSerializer(countries, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class CountryExistAPIView(APIView):
    def get(self, request, name):
        if not isinstance(name, str) or not name.strip():
            raise ValidationError("Country name is required.")

        trimmed_name = name.strip()
        exists = Country.objects.filter(name__iexact=trimmed_name).exists()
        return Response({"isExist": exists}, status=status.HTTP_200_OK)
