from django.contrib import admin
from .models import (
    Customer,
    CustomerLedgerEntry,
    Invoice,
    InvoiceItem,
    InvoicePayment,
    PaymentAllocation,
    Sale,
    SaleItem,
    SalesReturn,
    SalesReturnItem,
)


class SaleItemInline(admin.TabularInline):
    model = SaleItem
    extra = 0
    readonly_fields = ('unit_cost', 'line_total', 'line_profit')


@admin.register(Sale)
class SaleAdmin(admin.ModelAdmin):
    list_display = ('reference', 'customer', 'customer_name', 'total', 'payment_method', 'status', 'date', 'created_by')
    list_filter = ('status', 'payment_method', 'date')
    search_fields = ('reference', 'customer_name', 'customer__name')
    inlines = [SaleItemInline]
    date_hierarchy = 'date'

class InvoiceItemInline(admin.TabularInline):
    model = InvoiceItem
    extra = 0


class InvoicePaymentInline(admin.TabularInline):
    model = InvoicePayment
    extra = 0
    readonly_fields = ('created_by', 'created_at')


class PaymentAllocationInline(admin.TabularInline):
    model = PaymentAllocation
    extra = 0
    readonly_fields = ('created_by', 'created_at')


@admin.register(Invoice)
class InvoiceAdmin(admin.ModelAdmin):
    list_display = ('reference', 'customer', 'customer_name', 'total', 'total_paid', 'balance_due', 'status', 'issue_date', 'due_date')
    list_filter = ('status',)
    search_fields = ('reference', 'customer_name', 'customer__name')
    inlines = [InvoiceItemInline, InvoicePaymentInline, PaymentAllocationInline]
    date_hierarchy = 'issue_date'


@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    list_display = ('name', 'phone', 'email', 'is_active')
    list_filter = ('is_active',)
    search_fields = ('name', 'phone', 'email')


class SalesReturnItemInline(admin.TabularInline):
    model = SalesReturnItem
    extra = 0


@admin.register(SalesReturn)
class SalesReturnAdmin(admin.ModelAdmin):
    list_display = ('reference', 'sale', 'status', 'date', 'processed_date')
    list_filter = ('status',)
    search_fields = ('reference', 'sale__reference')
    inlines = [SalesReturnItemInline]


@admin.register(CustomerLedgerEntry)
class CustomerLedgerEntryAdmin(admin.ModelAdmin):
    list_display = (
        'date', 'customer', 'entry_type', 'reference',
        'debit', 'credit', 'created_by',
    )
    list_filter = ('entry_type', 'date')
    search_fields = ('customer__name', 'reference', 'note')


@admin.register(PaymentAllocation)
class PaymentAllocationAdmin(admin.ModelAdmin):
    list_display = ('payment', 'invoice', 'amount', 'created_by', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('invoice__reference', 'payment__invoice__reference')
