from django.contrib import admin, messages
from django.urls import path, reverse
from django.shortcuts import redirect
from .models import Client, Invoice, BindingRequest, APISettings
from .services import API_SYNC
from django.utils import timezone

@admin.register(Client)
class ClientAdmin(admin.ModelAdmin):
    list_display = ('name', 'club_card_number', 'telegram_id')
    change_list_template = "admin/clients_change_list.html"
    
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('sync-clients/', self.admin_site.admin_view(self.sync_clients), name='sync_clients'),
        ]
        return custom_urls + urls
    
    def sync_clients(self, request):
        syncer = API_SYNC()
        new_count = syncer.sync_clients()
        self.message_user(request, f"Синхронизировано. Добавлено новых клиентов: {new_count}", level=messages.INFO)
        return redirect("..")


@admin.register(Invoice)
class InvoiceAdmin(admin.ModelAdmin):
    list_display = ('api_id', 'client_name', 'sum', 'created_at', 'closed_at')
    change_list_template = "admin/invoices_change_list.html"

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('sync-invoices/', self.admin_site.admin_view(self.sync_invoices), name='sync_invoices'),
        ]
        return custom_urls + urls

    def sync_invoices(self, request):
        syncer = API_SYNC()
        count = syncer.sync_invoices()
        self.message_user(request, f"Синхронизировано. Обновлено/создано записей: {count}", level=messages.INFO)
        return redirect("..")

@admin.action(description="Подтвердить выбранные заявки и обновить Telegram ID клиента")
def approve_binding_requests(modeladmin, request, queryset):
    count = 0
    for binding_request in queryset:
        if binding_request.status != 'approved':
            binding_request.status = 'approved'
            binding_request.processed_at = timezone.now()
            binding_request.save()
            # Если у заявки связан клиент, обновляем его Telegram ID
            if binding_request.client:
                client = binding_request.client
                client.telegram_id = binding_request.telegram_chat_id
                client.save()
            count += 1
    modeladmin.message_user(request, f"Подтверждено {count} заявок", level=messages.INFO)

@admin.register(BindingRequest)
class BindingRequestAdmin(admin.ModelAdmin):
    list_display = ('client_card', 'client', 'telegram_chat_id', 'status', 'created_at')
    actions = [approve_binding_requests]
    change_list_template = "admin/bindingrequests_change_list.html"

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            # Пример кастомного URL для синхронизации заявок через API, если требуется
            path('sync-requests/', self.admin_site.admin_view(self.sync_requests), name='sync_requests'),
        ]
        return custom_urls + urls

    def sync_requests(self, request):
        syncer = API_SYNC()
        count = syncer.sync_binding_requests()
        self.message_user(request, f"Синхронизировано. Обновлено/создано записей: {count}", level=messages.INFO)
        return redirect("..")

    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        # Например, можно добавить количество заявок в контекст:
        extra_context['total_requests'] = BindingRequest.objects.count()
        return super().changelist_view(request, extra_context=extra_context)
    
@admin.register(APISettings)
class APISettingsAdmin(admin.ModelAdmin):
    list_display = ('api_url', 'api_key')
