from django.contrib.admin import register
from django.db.models import QuerySet
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _
from unfold.admin import ModelAdmin, TabularInline

from engine.core.admin import ActivationActionsMixin
from engine.payments.forms import GatewayForm, TransactionForm
from engine.payments.models import Balance, Gateway, Transaction


class TransactionInline(TabularInline):
    model = Transaction
    form = TransactionForm
    extra = 1
    is_navtab = True
    verbose_name = _("transaction")
    verbose_name_plural = _("transactions")

    def get_queryset(self, request: HttpRequest) -> QuerySet[Transaction]:
        qs = super().get_queryset(request)
        return qs.select_related("order")


@register(Balance)
class BalanceAdmin(ActivationActionsMixin, ModelAdmin):
    inlines = (TransactionInline,)
    list_display = ("user", "amount")
    search_fields = ("user__email",)
    ordering = ("user",)

    def get_queryset(self, request: HttpRequest) -> QuerySet[Balance]:
        qs = super().get_queryset(request)
        return qs.prefetch_related("transactions", "user")


@register(Transaction)
class TransactionAdmin(ActivationActionsMixin, ModelAdmin):
    list_display = ("balance", "amount", "order", "modified", "created")
    search_fields = ("balance__user__email", "currency", "payment_method")
    list_filter = ("currency", "payment_method")
    ordering = ("balance",)
    form = TransactionForm


@register(Gateway)
class GatewayAdmin(ActivationActionsMixin, ModelAdmin):
    list_display = (
        "name",
        "can_be_used",
        "is_active",
    )
    search_fields = (
        "name",
        "default_currency",
    )
    ordering = ("name",)
    form = GatewayForm

    def can_be_used(self, obj: Gateway) -> bool:
        return obj.can_be_used

    can_be_used.boolean = True  # ty: ignore[unresolved-attribute]
    can_be_used.short_description = _("can be used")  # ty: ignore[unresolved-attribute]
