from django.contrib import admin

from apps.core.admin_tools import JournalAdmin, ProtectedAdmin, SmartAdmin, register

from .models import (Activity, Budget, BudgetCategory, BudgetLine, Commitment,
                     Expense, FinancialEvent, FiscalYear, FundingSource, Payment,
                     Revenue, Threshold)


class BudgetLineInline(admin.TabularInline):
    model = BudgetLine
    extra = 0
    fields = ("category", "activity", "funding_source", "planned_xaf", "approved_xaf")


@admin.register(Budget)
class BudgetAdmin(ProtectedAdmin):
    list_display = ("code", "agency", "fiscal_year", "version_number", "status", "total_xaf")
    list_filter = ("status", "agency")
    search_fields = ("code",)
    list_select_related = ("agency", "fiscal_year")
    inlines = [BudgetLineInline]


@admin.register(Expense)
class ExpenseAdmin(ProtectedAdmin):
    list_display = ("code", "label", "agency", "amount_xaf", "incurred_on", "status")
    list_filter = ("status", "agency", "category")
    search_fields = ("code", "label", "supplier_name", "invoice_ref")
    list_select_related = ("agency",)
    date_hierarchy = "incurred_on"


register(FinancialEvent, JournalAdmin, list_display=("ledger_seq", "event_type", "agency", "amount_xaf", "created_at"),
         list_filter=("event_type", "agency"), list_select_related=("agency",), date_hierarchy="created_at")
register(Revenue, ProtectedAdmin, list_display=("code", "label", "agency", "amount_xaf", "received_on", "status"),
         list_filter=("status", "agency"), search_fields=("code", "label", "reference"))
register(Payment, JournalAdmin, list_display=("code", "agency", "expense", "amount_xaf", "method", "paid_on", "status"),
         list_filter=("method", "status", "agency"), list_select_related=("agency", "expense"))
register(FiscalYear, ProtectedAdmin)
register(BudgetCategory, SmartAdmin)
register(Activity, SmartAdmin)
register(FundingSource, SmartAdmin)
register(BudgetLine, ProtectedAdmin, list_display=("budget", "category", "planned_xaf", "approved_xaf"),
         list_select_related=("budget", "category"))
register(Commitment, ProtectedAdmin)
register(Threshold, SmartAdmin, list_display=("scope", "agency", "min_amount", "max_amount", "required_approvals",
                                              "allow_self_approval", "is_active"))
