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

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


class TransactionInline(admin.TabularInline):  # type: ignore [type-arg]
    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):  # type: ignore [misc, type-arg]
    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):  # type: ignore [misc, type-arg]
    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
