from django.contrib import admin
from .models import APILog
import pytz
from django.utils import timezone
from django.http import JsonResponse
from .models import PendingOrder
from .utils import get_pending_orders
from django.http import HttpResponseRedirect

# Custom Admin Site to reorder the app list
class CustomAdminSite(admin.AdminSite):
    def get_app_list(self, request):
        app_list = super().get_app_list(request)

        # Find "Skyplay API" and move it to the end
        skyplay_api_app = None
        other_apps = []

        for app in app_list:
            if app["name"] == "skyplay_api":
                skyplay_api_app = app
            else:
                other_apps.append(app)

        # Ensure "Skyplay API" is moved to the last position
        if skyplay_api_app:
            other_apps.append(skyplay_api_app)

        return other_apps

# Instantiate the custom admin site
custom_admin_site = CustomAdminSite(name="custom_admin")

@admin.register(APILog)
class APILogAdmin(admin.ModelAdmin):
    list_display = ('client_id', 'endpoint', 'status_code', 'timestamp_ist')  # Use IST display
    search_fields = ('user__username', 'endpoint', 'request_data', 'response_data')
    ordering = ('-timestamp',)

    def timestamp_ist(self, obj):
        ist = pytz.timezone('Asia/Kolkata')
        return obj.timestamp.astimezone(ist).strftime("%Y-%m-%d %H:%M:%S")
    timestamp_ist.short_description = "Timestamp (IST)"


class PendingOrderAdmin(admin.ModelAdmin):
    list_display = ('order_id', 'client_id', 'amount', 'status', 'created_at', 'updated_at')
    change_list_template = "skyplay_api/admin/pendingorder_changelist.html"

    def convert_to_ist(self, dt):
        """
        Convert UTC datetime to IST (Indian Standard Time).
        """
        if dt is not None:
            # Set timezone to UTC, then convert it to IST
            utc_zone = pytz.utc
            ist_zone = pytz.timezone('Asia/Kolkata')
            dt = dt.replace(tzinfo=utc_zone)  # Ensure it's in UTC timezone
            dt_ist = dt.astimezone(ist_zone)  # Convert to IST
            return dt_ist.strftime('%Y-%m-%d %H:%M:%S')  # Return in the format you desire
        return dt

    def changelist_view(self, request, extra_context=None):
        if 'insert_pending' in request.GET:
            pending_orders = get_pending_orders()
            existing_orders = set(PendingOrder.objects.values_list('order_id', flat=True))

            for order in pending_orders:
                if order['id'] not in existing_orders:
                    PendingOrder.objects.create(
                        order_id=order['id'],
                        client_id=order['client_id'],
                        amount=order['amount'],
                        status=order['status'],
                        billing_cycle=order['billing_cycle'],
                        invoice_id=order['invoice_id'],
                        billing_from_date=order['billing_from_date'],
                        billing_to_date=order['billing_to_date'],
                        invoice_amount=order['invoice_amount'],
                    )

            # Remove completed/canceled orders
            PendingOrder.objects.filter(status__in=['paid', 'cancelled']).delete()

            self.message_user(request, "Pending orders synced successfully.")

            return HttpResponseRedirect(request.path)

        # Convert created_at and updated_at to IST before rendering in admin
        extra_context = extra_context or {}
        if 'pendingorder' in request.path:
            pending_orders = PendingOrder.objects.all()
            for order in pending_orders:
                order.created_at = self.convert_to_ist(order.created_at)
                order.updated_at = self.convert_to_ist(order.updated_at)

        return super().changelist_view(request, extra_context=extra_context)

admin.site.register(PendingOrder, PendingOrderAdmin)