# finance/admin.py
from django.contrib import admin
from .models import (
    FeeStructure, SchoolItemPrice, StudentEnrollmentFee,
    Invoice, InvoiceItem, Payment, PaymentReminder,
    Discount, StudentDiscount, ExpenseCategory, Expense, FinancialReport
)


# ---------------------------------------------------------------------------
# FeeStructure
# ---------------------------------------------------------------------------

@admin.register(FeeStructure)
class FeeStructureAdmin(admin.ModelAdmin):
    list_display  = [
        'name', 'section', 'class_group',
        'registration_new', 'registration_old',
        'total_fees', 'installment_1', 'installment_2',
        'academic_year', 'is_active',
    ]
    list_filter   = ['section', 'class_group', 'academic_year', 'is_active']
    search_fields = ['name', 'description']
    list_editable = ['is_active']
    filter_horizontal = ['specific_classes']
    date_hierarchy    = 'created_at'

    fieldsets = (
        ('Identity', {
            'fields': ('name', 'section', 'class_group', 'academic_year', 'is_active'),
        }),
        ('Registration Fees', {
            'description': 'Registration fee differs for new vs returning pupils.',
            'fields': ('registration_new', 'registration_old'),
        }),
        ('Annual Tuition & Installments', {
            'description': 'total_fees must equal installment_1 + installment_2.',
            'fields': ('total_fees', 'installment_1', 'installment_2'),
        }),
        ('Optional Class Links', {
            'fields': ('specific_classes',),
            'classes': ('collapse',),
        }),
        ('Notes', {
            'fields': ('description',),
            'classes': ('collapse',),
        }),
        ('Metadata', {
            'fields': ('created_by', 'created_at', 'updated_at'),
            'classes': ('collapse',),
        }),
    )
    readonly_fields = ['created_at', 'updated_at']


# ---------------------------------------------------------------------------
# SchoolItemPrice
# ---------------------------------------------------------------------------

@admin.register(SchoolItemPrice)
class SchoolItemPriceAdmin(admin.ModelAdmin):
    list_display  = ['name', 'item_type', 'price', 'academic_year', 'is_active']
    list_filter   = ['item_type', 'academic_year', 'is_active']
    list_editable = ['is_active']
    search_fields = ['name']


# ---------------------------------------------------------------------------
# StudentEnrollmentFee
# ---------------------------------------------------------------------------

@admin.register(StudentEnrollmentFee)
class StudentEnrollmentFeeAdmin(admin.ModelAdmin):
    list_display  = [
        'student', 'fee_structure', 'academic_year',
        'is_new_pupil', 'registration_fee', 'total_fees',
        'installment_1_due', 'installment_2_due',
    ]
    list_filter   = ['academic_year', 'is_new_pupil', 'fee_structure__section']
    search_fields = ['student__first_name', 'student__last_name', 'student__student_id']
    readonly_fields = ['registration_fee', 'total_fees', 'created_at']


# ---------------------------------------------------------------------------
# Invoice
# ---------------------------------------------------------------------------

class InvoiceItemInline(admin.TabularInline):
    model  = InvoiceItem
    extra  = 1
    fields = ['description', 'quantity', 'unit_price', 'discount', 'total']
    readonly_fields = ['total']


class PaymentInline(admin.TabularInline):
    model  = Payment
    extra  = 0
    readonly_fields = ['payment_number', 'created_at']
    fields = ['payment_number', 'amount', 'payment_method', 'payment_date', 'status']


@admin.register(Invoice)
class InvoiceAdmin(admin.ModelAdmin):
    list_display  = [
        'invoice_number', 'student', 'academic_year', 'invoice_type',
        'total_amount', 'amount_paid', 'balance', 'status', 'due_date',
    ]
    list_filter   = ['status', 'academic_year', 'invoice_type', 'issue_date']
    search_fields = ['invoice_number', 'student__first_name', 'student__last_name']
    readonly_fields = ['invoice_number', 'balance', 'created_at', 'updated_at']
    inlines       = [InvoiceItemInline, PaymentInline]
    date_hierarchy = 'issue_date'

    fieldsets = (
        ('Invoice Information', {
            'fields': ('invoice_number', 'student', 'enrollment_fee', 'academic_year', 'invoice_type'),
        }),
        ('Dates', {
            'fields': ('issue_date', 'due_date'),
        }),
        ('Amounts', {
            'fields': ('total_amount', 'amount_paid', 'balance'),
        }),
        ('Status & Notes', {
            'fields': ('status', 'notes'),
        }),
        ('Metadata', {
            'fields': ('created_by', 'created_at', 'updated_at', 'last_reminder_sent'),
            'classes': ('collapse',),
        }),
    )


# ---------------------------------------------------------------------------
# Payment
# ---------------------------------------------------------------------------

@admin.register(Payment)
class PaymentAdmin(admin.ModelAdmin):
    list_display  = [
        'payment_number', 'invoice', 'student', 'amount',
        'payment_method', 'payment_date', 'status',
    ]
    list_filter   = ['payment_method', 'status', 'payment_date']
    search_fields = ['payment_number', 'invoice__invoice_number', 'student__first_name']
    readonly_fields = ['payment_number', 'created_at', 'updated_at']
    date_hierarchy = 'payment_date'

    fieldsets = (
        ('Payment Information', {
            'fields': ('payment_number', 'invoice', 'student', 'amount'),
        }),
        ('Payment Details', {
            'fields': ('payment_method', 'payment_date', 'transaction_id'),
        }),
        ('Mobile Money', {
            'fields': ('mobile_money_provider', 'mobile_money_number'),
            'classes': ('collapse',),
        }),
        ('Bank / Cheque', {
            'fields': ('bank_name', 'cheque_number'),
            'classes': ('collapse',),
        }),
        ('Receipt', {
            'fields': ('receipt_number', 'receipt_issued', 'receipt_issued_date'),
        }),
        ('Status & Notes', {
            'fields': ('status', 'notes'),
        }),
        ('Metadata', {
            'fields': ('received_by', 'created_at', 'updated_at'),
            'classes': ('collapse',),
        }),
    )


# ---------------------------------------------------------------------------
# Discount / StudentDiscount
# ---------------------------------------------------------------------------

@admin.register(Discount)
class DiscountAdmin(admin.ModelAdmin):
    list_display  = ['name', 'discount_type', 'value', 'applies_to', 'is_active']
    list_filter   = ['discount_type', 'applies_to', 'is_active']
    search_fields = ['name', 'description']
    filter_horizontal = ['specific_fees']


@admin.register(StudentDiscount)
class StudentDiscountAdmin(admin.ModelAdmin):
    list_display  = ['student', 'discount', 'academic_year', 'approved_by']
    list_filter   = ['academic_year']
    search_fields = ['student__first_name', 'student__last_name']


# ---------------------------------------------------------------------------
# Expenses
# ---------------------------------------------------------------------------

@admin.register(ExpenseCategory)
class ExpenseCategoryAdmin(admin.ModelAdmin):
    list_display  = ['name', 'name_fr', 'is_active']
    list_filter   = ['is_active']
    search_fields = ['name']


@admin.register(Expense)
class ExpenseAdmin(admin.ModelAdmin):
    list_display  = [
        'expense_number', 'category', 'description',
        'amount', 'expense_date', 'payment_method',
    ]
    list_filter   = ['category', 'payment_method', 'expense_date']
    search_fields = ['expense_number', 'description', 'vendor']
    date_hierarchy = 'expense_date'
    readonly_fields = ['expense_number', 'created_at', 'updated_at']


# ---------------------------------------------------------------------------
# Financial Report
# ---------------------------------------------------------------------------

@admin.register(FinancialReport)
class FinancialReportAdmin(admin.ModelAdmin):
    list_display  = [
        'title', 'report_type', 'start_date', 'end_date',
        'total_revenue', 'total_expenses', 'net_profit',
    ]
    list_filter   = ['report_type', 'generated_at']
    readonly_fields = ['generated_at']