from django.contrib import admin
from .models import BankAccount, Payee, Check, Category
from django.http import HttpResponse
import csv
from django.contrib.admin import DateFieldListFilter


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ("name",)


@admin.register(BankAccount)
class BankAccountAdmin(admin.ModelAdmin):
    list_display = (
        "account_nickname",
        "institution_name",
        "account_number",
        "routing_number",
        "city",
    )


@admin.register(Payee)
class PayeeAdmin(admin.ModelAdmin):
    list_display = ("name", "city")


@admin.register(Check)
class CheckAdmin(admin.ModelAdmin):
    list_display = ("check_number", "payee", "bank_account", "amount", "check_date")
    readonly_fields = ("check_number", "pdf")
    search_fields = ("check_number", "payee__name", "bank_account__name")
    list_filter = ("bank_account", "payee", ("check_date", DateFieldListFilter))
    actions = ["export_to_monarchmoney_csv"]

    def export_to_monarchmoney_csv(self, request, queryset):
        response = HttpResponse(content_type="text/csv")
        response["Content-Disposition"] = "attachment; filename=checks_monarchmoney.csv"
        writer = csv.writer(response)
        writer.writerow(
            [
                "Date",
                "Merchant",
                "Category",
                "Account",
                "Original Statement",
                "Notes",
                "Amount",
                "Tags",
            ]
        )
        for check in queryset:
            date = check.check_date.strftime("%Y-%m-%d")
            merchant = check.payee.name
            category = check.category.name if check.category else ""
            account = (
                check.bank_account.account_nickname
                or check.bank_account.institution_name
            )
            original_statement = (
                f"{check.payee.name} - {check.payee.payor_account_number}"
            )
            notes = f"{check.check_number} - {check.payee.name} - {check.payee.payor_account_number} - {check.memo} - {check.invoice}"
            amount = f"{check.amount:.2f}"
            tags = (
                ", ".join(tag.name for tag in check.tags.all())
                if hasattr(check, "tags")
                else ""
            )
            writer.writerow(
                [
                    date,
                    merchant,
                    category,
                    account,
                    original_statement,
                    notes,
                    amount,
                    tags,
                ]
            )
        return response

    export_to_monarchmoney_csv.short_description = (
        "Export selected checks to MonarchMoney CSV"
    )
