import requests
from django.conf import settings
from django.contrib import admin
from .models import FacebookPageAssistant
from .services import FacebookService  # Import FacebookService for API calls

@admin.register(FacebookPageAssistant)
class FacebookPageAssistantAdmin(admin.ModelAdmin):
    """
    Admin panel configuration for managing Facebook Page Assistants.
    """
    list_display = ("page_name", "page_id", "assistant", "is_subscribed", "created_at")
    search_fields = ("page_name", "page_id", "assistant__name")
    list_filter = ("is_subscribed", "assistant")
    actions = ["subscribe_to_webhook", "check_subscription_status"]

    def subscribe_to_webhook(self, request, queryset):
        """
        Subscribes selected pages to Facebook webhooks using FacebookService.
        """
        fb_service = FacebookService(user_access_token=settings.PAGE_ACCESS_TOKEN)

        for page in queryset:
            page_access_token = fb_service.get_page_access_token(page.page_id)
            if not page_access_token:
                self.message_user(request, f"Failed to get access token for {page.page_name}", level="error")
                continue

            url = f"https://graph.facebook.com/v22.0/{page.page_id}/subscribed_apps"
            data = {
                "subscribed_fields": "feed,mention",
                "access_token": page_access_token
            }

            try:
                response = requests.post(url, data=data)
                response.raise_for_status()
                page.is_subscribed = True
                page.save()
                self.message_user(request, f"Successfully subscribed {page.page_name} to webhooks.")
            except requests.RequestException as e:
                self.message_user(request, f"Failed to subscribe {page.page_name}: {e}", level="error")

    subscribe_to_webhook.short_description = "Subscribe selected pages to webhooks"

    def check_subscription_status(self, request, queryset):
        """
        Checks whether selected pages are subscribed to Facebook webhooks using FacebookService.
        """
        fb_service = FacebookService(user_access_token=settings.PAGE_ACCESS_TOKEN)

        for page in queryset:
            page_access_token = fb_service.get_page_access_token(page.page_id)
            if not page_access_token:
                self.message_user(request, f"Failed to get access token for {page.page_name}", level="error")
                continue

            url = f"https://graph.facebook.com/v22.0/{page.page_id}/subscribed_apps?access_token={page_access_token}"

            try:
                response = requests.get(url)
                response.raise_for_status()
                data = response.json()

                if "data" in data and len(data["data"]) > 0:
                    page.is_subscribed = True
                    self.message_user(request, f"{page.page_name} is subscribed.")
                else:
                    page.is_subscribed = False
                    self.message_user(request, f"{page.page_name} is NOT subscribed.", level="warning")

                page.save()
            except requests.RequestException as e:
                self.message_user(request, f"Failed to check subscription for {page.page_name}: {e}", level="error")

    check_subscription_status.short_description = "Check webhook subscription status"
