from django.http import HttpRequest, JsonResponse
from django.urls import reverse
from django.views.generic import TemplateView

from .filters import ParkFilter
from .forms import ParkSearchForm
from .querysets import get_base_park_queryset


class ParkSearchView(TemplateView):
    """View for handling park search with autocomplete."""

    template_name = "parks/park_list.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["search_form"] = ParkSearchForm(self.request.GET)

        # Initialize filter with current querystring
        queryset = get_base_park_queryset()
        filter_instance = ParkFilter(self.request.GET, queryset=queryset)
        context["filter"] = filter_instance

        # Apply search if park ID selected via autocomplete
        park_id = self.request.GET.get("park")
        queryset = filter_instance.qs.filter(id=park_id) if park_id else filter_instance.qs

        # Handle view mode
        context["view_mode"] = self.request.GET.get("view_mode", "grid")
        context["parks"] = queryset

        return context


def suggest_parks(request: HttpRequest) -> JsonResponse:
    """Return park search suggestions as JSON."""
    query = request.GET.get("search", "").strip()
    if not query:
        return JsonResponse({"results": []})

    queryset = get_base_park_queryset()
    filter_instance = ParkFilter({"search": query}, queryset=queryset)
    parks = filter_instance.qs[:8]  # Limit to 8 suggestions

    results = [
        {
            "id": str(park.pk),
            "name": park.name,
            "status": park.get_status_display(),
            "location": park.formatted_location or "",
            "url": reverse("parks:park_detail", kwargs={"slug": park.slug}),
        }
        for park in parks
    ]

    return JsonResponse({"results": results})
