from django.utils import timezone
from rest_framework import viewsets
from .models import State, Locality, Area, Location
from .serializers import StateSerializer, LocalitySerializer, AreaSerializer, LocationSerializer

class StateViewSet(viewsets.ModelViewSet):
    """
    API لعرض وتعديل الولايات مع Soft Delete
    """
    queryset = State.objects.all().order_by('-created_at')
    serializer_class = StateSerializer

    def perform_create(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(created_by=self.request.user)
        else:
            serializer.save()

    def perform_update(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(updated_by=self.request.user)
        else:
            serializer.save()

    def perform_destroy(self, instance):
        instance.deleted_at = timezone.now()
        if self.request.user.is_authenticated:
            instance.deleted_by = self.request.user
        instance.save()


class LocalityViewSet(viewsets.ModelViewSet):

    queryset = Locality.objects.select_related('state').filter(state__deleted_at__isnull=True).order_by('state__name', 'name')
    serializer_class = LocalitySerializer

    def perform_create(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(created_by=self.request.user)
        else:
            serializer.save()

    def perform_update(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(updated_by=self.request.user)
        else:
            serializer.save()

    def perform_destroy(self, instance):
        instance.deleted_at = timezone.now()
        if self.request.user.is_authenticated:
            instance.deleted_by = self.request.user
        instance.save()

class AreaViewSet(viewsets.ModelViewSet):
    queryset = Area.objects.select_related('locality__state').filter(locality__deleted_at__isnull=True).order_by('locality__state__name', 'locality__name', 'name')
    serializer_class = AreaSerializer

    def perform_create(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(created_by=self.request.user)
        else:
            serializer.save()

    def perform_update(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(updated_by=self.request.user)
        else:
            serializer.save()

    def perform_destroy(self, instance):
        instance.deleted_at = timezone.now()
        if self.request.user.is_authenticated:
            instance.deleted_by = self.request.user
        instance.save()
#Mo
class LocationViewSet(viewsets.ModelViewSet):
    queryset = Location.objects.select_related('area__locality__state').filter(area__deleted_at__isnull=True).order_by(
        'area__locality__state__name', 'area__locality__name', 'area__name', 'name'
    )
    serializer_class = LocationSerializer

    def perform_create(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(created_by=self.request.user)
        else:
            serializer.save()

    def perform_update(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(updated_by=self.request.user)
        else:
            serializer.save()

    def perform_destroy(self, instance):
        instance.deleted_at = timezone.now()
        if self.request.user.is_authenticated:
            instance.deleted_by = self.request.user
        instance.save()

from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db.models import Q

def locality_datatable_test_api(request):
    draw = int(request.GET.get('draw', 1))
    start = int(request.GET.get('start', 0))
    length = int(request.GET.get('length', 10))
    search_value = request.GET.get('search[value]', '')
    filter_state = request.GET.get('filter_state', '')

    queryset = Locality.objects.select_related('state').filter(state__deleted_at__isnull=True)

    if filter_state and filter_state.isdigit():
        queryset = queryset.filter(state_id=int(filter_state))

    if search_value:
        queryset = queryset.filter(
            Q(name__icontains=search_value) |
            Q(code__icontains=search_value) |
            Q(state__name__icontains=search_value)
        )


    queryset = queryset.order_by('state__name', 'name')

    paginator = Paginator(queryset, length)
    page_number = (start // length) + 1
    page = paginator.get_page(page_number)

    data = []
    for obj in page:
        data.append({
            'id': obj.id,
            'name': obj.name,
            'code': obj.code,
            'state_name': obj.state.name,
            'created_at': obj.created_at.strftime('%Y-%m-%d %H:%M') if obj.created_at else '',
        })

    return JsonResponse({
        'draw': draw,
        'recordsTotal': paginator.count,
        'recordsFiltered': paginator.count,
        'data': data,
    })


def areas_datatable_api(request):
    draw = int(request.GET.get('draw', 1))
    start = int(request.GET.get('start', 0))
    length = int(request.GET.get('length', 10))
    search_value = request.GET.get('search[value]', '')
    filter_locality = request.GET.get('filter_locality', '')

    queryset = Area.objects.select_related('locality__state').filter(
        locality__deleted_at__isnull=True
    )

    if filter_locality and filter_locality.isdigit():
        queryset = queryset.filter(locality_id=int(filter_locality))

    if search_value:
        queryset = queryset.filter(
            Q(name__icontains=search_value) |
            Q(code__icontains=search_value) |
            Q(locality__name__icontains=search_value) |
            Q(locality__state__name__icontains=search_value)
        )

    # ترتيب
    order_column_index = request.GET.get('order[0][column]')
    order_dir = request.GET.get('order[0][dir]', 'asc')
    columns = ['id', 'name', 'code', 'locality__name', 'locality__state__name', 'created_at']

    if order_column_index and order_column_index.isdigit():
        idx = int(order_column_index)
        if 0 <= idx < len(columns):
            order_field = columns[idx]
            if order_dir == 'desc':
                order_field = '-' + order_field
            queryset = queryset.order_by(order_field)
        else:
            queryset = queryset.order_by('locality__state__name', 'locality__name', 'name')
    else:
        queryset = queryset.order_by('locality__state__name', 'locality__name', 'name')

    paginator = Paginator(queryset, length)
    page_number = (start // length) + 1
    page = paginator.get_page(page_number)

    data = []
    for obj in page:
        data.append({
            'id': obj.id,
            'name': obj.name,
            'code': obj.code,
            'locality_name': obj.locality.name,
            'state_name': obj.locality.state.name,
            'created_at': obj.created_at.strftime('%Y-%m-%d %H:%M') if obj.created_at else '',
        })

    return JsonResponse({
        'draw': draw,
        'recordsTotal': paginator.count,
        'recordsFiltered': paginator.count,
        'data': data,
    })


def locations_datatable_api(request):
    draw = int(request.GET.get('draw', 1))
    start = int(request.GET.get('start', 0))
    length = int(request.GET.get('length', 10))
    search_value = request.GET.get('search[value]', '')
    filter_area = request.GET.get('filter_area', '')

    queryset = Location.objects.select_related('area__locality__state').filter(area__deleted_at__isnull=True)

    if filter_area and filter_area.isdigit():
        queryset = queryset.filter(area_id=int(filter_area))

    if search_value:
        queryset = queryset.filter(
            Q(name__icontains=search_value) |
            Q(code__icontains=search_value) |
            Q(area__name__icontains=search_value) |
            Q(area__locality__name__icontains=search_value) |
            Q(area__locality__state__name__icontains=search_value)
        )

    # Sorting (simplified; you can implement ordering as needed)
    queryset = queryset.order_by('area__locality__state__name', 'area__locality__name', 'area__name', 'name')

    paginator = Paginator(queryset, length)
    page_number = (start // length) + 1
    page = paginator.get_page(page_number)

    data = []
    for obj in page:
        data.append({
            'id': obj.id,
            'name': obj.name,
            'code': obj.code,
            'area_name': obj.area.name,
            'locality_name': obj.area.locality.name,
            'state_name': obj.area.locality.state.name,
            'zoning': obj.get_zoning_display() if obj.zoning else '',
            'latitude': str(obj.latitude) if obj.latitude else '',
            'longitude': str(obj.longitude) if obj.longitude else '',
            'created_at': obj.created_at.strftime('%Y-%m-%d %H:%M') if obj.created_at else '',
        })

    return JsonResponse({
        'draw': draw,
        'recordsTotal': paginator.count,
        'recordsFiltered': paginator.count,
        'data': data,
    })

from django.shortcuts import render

def home_page(request):
    return render(request, 'home.html')

def states_page(request):
    return render(request, 'states.html')

def localities_page(request):
    return render(request, 'localities.html')
def areas_page(request):
    return render(request, 'areas.html')
def locations_page(request):
    return render(request, 'locations.html')
