from django.views.generic import DetailView, ListView
from django.shortcuts import get_object_or_404
from django.core.serializers.json import DjangoJSONEncoder
from django.urls import reverse
from .models import Park, ParkArea
from rides.models import Ride
from core.views import SlugRedirectMixin

class ParkDetailView(SlugRedirectMixin, DetailView):
    model = Park
    template_name = 'parks/park_detail.html'
    context_object_name = 'park'

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()
        slug = self.kwargs.get(self.slug_url_kwarg)
        # Try to get by current or historical slug
        return self.model.get_by_slug(slug)[0]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['rides'] = Ride.objects.filter(
            park=self.object
        ).select_related('coaster_stats')
        context['areas'] = ParkArea.objects.filter(park=self.object)
        return context

    def get_redirect_url_pattern(self):
        return 'park_detail'

class ParkAreaDetailView(SlugRedirectMixin, DetailView):
    model = ParkArea
    template_name = 'parks/area_detail.html'
    context_object_name = 'area'
    slug_url_kwarg = 'area_slug'

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()
        park_slug = self.kwargs.get('park_slug')
        area_slug = self.kwargs.get('area_slug')
        # Try to get by current or historical slug
        obj, is_old_slug = self.model.get_by_slug(area_slug)
        if obj.park.slug != park_slug:
            raise self.model.DoesNotExist("Park slug doesn't match")
        return obj

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['rides'] = Ride.objects.filter(
            area=self.object
        ).select_related('coaster_stats')
        return context

    def get_redirect_url_pattern(self):
        return 'area_detail'

    def get_redirect_url_kwargs(self):
        return {
            'park_slug': self.object.park.slug,
            'area_slug': self.object.slug
        }

class ParkListView(ListView):
    model = Park
    template_name = 'parks/park_list.html'
    context_object_name = 'parks'

    def get_queryset(self):
        queryset = Park.objects.select_related('owner').prefetch_related('photos', 'rides')
        
        # Apply filters
        search = self.request.GET.get('search', '').strip()
        location = self.request.GET.get('location', '').strip()
        status = self.request.GET.get('status', '').strip()
        
        if search:
            queryset = queryset.filter(name__icontains=search) | queryset.filter(location__icontains=search)
        if location:
            queryset = queryset.filter(location=location)
        if status:
            queryset = queryset.filter(status=status)
            
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get unique locations for filter dropdown
        context['locations'] = list(Park.objects.values_list('location', flat=True)
                                  .distinct().order_by('location'))
        
        # Add current filter values to context
        context['current_filters'] = {
            'search': self.request.GET.get('search', ''),
            'location': self.request.GET.get('location', ''),
            'status': self.request.GET.get('status', '')
        }
        
        return context

    def get(self, request, *args, **kwargs):
        # Check if this is an HTMX request
        if request.htmx:
            # If it is, return just the parks list partial
            self.template_name = 'parks/partials/park_list.html'
        return super().get(request, *args, **kwargs)
