from datetime import date

from django.contrib import admin
from wbcore.contrib.directory.models import Entry

from wbaccounting.models import BookingEntry, Invoice
from wbaccounting.models.booking_entry import BookingEntryType


class BookingEntryInline(admin.TabularInline):
    model = BookingEntry
    fields = ("type", "period", "booking_date", "gross_value", "vat", "net_value")
    readonly_fields = ("net_value",)
    ordering = ("vat", "type")
    extra = 0
    show_change_link = True

    def has_add_permission(self, request, obj=None):
        return False


@admin.register(BookingEntryType)
class BookingEntryTypeModelAdmin(admin.ModelAdmin):
    pass


@admin.register(BookingEntry)
class BookingEntryModelAdmin(admin.ModelAdmin):
    list_display = (
        "product",
        "type",
        "period",
        "booking_date",
        "net_value",
        "vat",
        "currency",
        "payment_date",
        "counterparty",
        "reference_date",
    )
    search_fields = ["counterparty__computed_str"]
    raw_id_fields = ("counterparty", "currency", "invoice")
    autocomplete_fields = ("counterparty", "currency", "invoice")

    fieldsets = (
        (
            "Basic Information",
            {
                "fields": ("product", "type", "account"),
                "classes": ("wide",),
            },
        ),
        (
            "Period & Dates",
            {
                "fields": ("period", "booking_date", "due_date", "payment_date", "reference_date"),
                "classes": ("wide"),
                "description": "Key dates for the booking entry.",
            },
        ),
        (
            "Amounts",
            {
                "fields": (
                    ("gross_value", "net_value", "vat"),
                    ("quantity",),
                ),
                "classes": ("wide"),
                "description": "Gross or Net value (Net preferred if both set). Negative values indicate payment.",
            },
        ),
        (
            "Invoice Details",
            {
                "fields": (
                    ("invoice_gross_value", "invoice_net_value"),
                    ("invoice_fx_rate",),
                    "invoice",
                ),
                "classes": ("collapse",),
            },
        ),
        (
            "Parties & Currency",
            {
                "fields": ("counterparty", "currency"),
                "classes": ("wide",),
            },
        ),
        (
            "Advanced",
            {
                "fields": ("backlinks", "parameters"),
                "classes": ("collapse",),
                "description": "JSON fields for backlinks and extra parameters.",
            },
        ),
    )

    # TODO: Remove or adjust.
    def create_invoice(self, request, queryset):
        counterparty = list(set(queryset.values_list("counterparty__id", flat=True)))
        if len(counterparty) == 1:
            counterparty = Entry.objects.get(id=counterparty[0])
            invoice = Invoice.objects.create(
                title=f"Rebate Invoice {counterparty.computed_str} ({queryset.earliest('from_date').from_date:%d.%m.%Y} - {queryset.latest('to_date').to_date:%d.%m.%Y})",
                invoice_date=date.today(),
                reference_date=date.today(),
                counterparty=counterparty,
                invoice_currency=counterparty.entry_accounting_information.default_currency,
                is_counterparty_invoice=True,
            )
            for booking_entry in queryset:
                booking_entry.invoice = invoice
                booking_entry.save()
            invoice.save()

        else:
            print("-------------------------------")  # noqa: T201
            print(f"Too many counterparties selected ({len(counterparty)})")  # noqa: T201
            print("-------------------------------")  # noqa: T201

    actions = [create_invoice]
