from django.contrib import admin
from django import forms
from .models import FinanceEntry

class MemberUserChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, user):
        member = getattr(user, "member_profile", None)
        if member:
            name = " ".join(part for part in (member.first_name, member.other_names, member.last_name) if part)
            return name or member.primary_phone
        return user.get_full_name() or user.phone_number

class FinanceEntryAdminForm(forms.ModelForm):
    class Meta:
        model = FinanceEntry
        fields = "__all__"

    submitted_by = MemberUserChoiceField(
        queryset=FinanceEntry._meta.get_field("submitted_by").remote_field.model.objects.select_related("member_profile").all()
    )

@admin.register(FinanceEntry)
class FinanceEntryAdmin(admin.ModelAdmin):
    form = FinanceEntryAdminForm
    list_display = ("description", "direction", "category", "formatted_amount", "transaction_date", "campus", "submitted_by_name", "approved")
    list_filter = ("approved", "direction", "category", "scope", "campus", "transaction_date")
    search_fields = ("description", "reference", "submitted_by__phone_number")
    date_hierarchy = "transaction_date"
    list_editable = ("approved",)
    readonly_fields = ("submitted_at",)
    list_select_related = ("campus", "submitted_by", "submitted_by__member_profile")

    @admin.display(description="Amount", ordering="amount")
    def formatted_amount(self, obj): return f"{obj.currency} {obj.amount:,.2f}"

    @admin.display(description="Submitted by", ordering="submitted_by__member_profile__first_name")
    def submitted_by_name(self, obj):
        member = getattr(obj.submitted_by, "member_profile", None)
        if member:
            return " ".join(part for part in (member.first_name, member.other_names, member.last_name) if part)
        return obj.submitted_by.get_full_name() or obj.submitted_by.phone_number
