from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db.models import Q
from django.utils import timezone
from rest_framework import viewsets

from .models import Establishment, EstablishmentType
from .serializers import EstablishmentSerializer, EstablishmentTypeSerializer


# -------------------------------
# 1. ViewSet لأنواع المنشآت (للقراءة فقط)
# -------------------------------
class EstablishmentTypeViewSet(viewsets.ModelViewSet):
    """API لعرض أنواع المنشآت (للاستخدام في القوائم المنسدلة)"""
    queryset = EstablishmentType.objects.all()
    serializer_class = EstablishmentTypeSerializer


# -------------------------------
# 2. ViewSet للمنشآت (CRUD كامل مع Soft Delete)
# -------------------------------
class EstablishmentViewSet(viewsets.ModelViewSet):
    queryset = Establishment.objects.all().order_by('-created_at')
    serializer_class = EstablishmentSerializer

    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()


# -------------------------------
# 3. API مخصص لـ DataTables (Server-side)
# -------------------------------
def establishments_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_location = request.GET.get('filter_location', '')

    queryset = Establishment.objects.select_related(
        'location__area__locality__state',
        'establishment_type'
    ).all()

    if filter_location and filter_location.isdigit():
        queryset = queryset.filter(location_id=int(filter_location))

    if search_value:
        queryset = queryset.filter(
            Q(name_ar__icontains=search_value) |
            Q(name_en__icontains=search_value) |
            Q(license_number__icontains=search_value) |
            Q(owner_name__icontains=search_value) |
            Q(location__name__icontains=search_value) |
            Q(location__area__name__icontains=search_value) |
            Q(location__area__locality__name__icontains=search_value) |
            Q(location__area__locality__state__name__icontains=search_value)
        )

    # ترتيب افتراضي
    queryset = queryset.order_by('-created_at')

    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_ar': obj.name_ar,
            'name_en': obj.name_en or '',
            'establishment_type': obj.establishment_type.name if obj.establishment_type else '',
            'location_name': obj.location.name,
            'area_name': obj.location.area.name,
            'locality_name': obj.location.area.locality.name,
            'state_name': obj.location.area.locality.state.name,
            'license_number': obj.license_number or '',
            'owner_name': obj.owner_name or '',
            'phone': obj.phone or '',
            'address': obj.address or '',
            '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,
    })


# -------------------------------
# 4. صفحة HTML للمنشآت
# -------------------------------
def establishments_page(request):
    return render(request, 'establishments.html')