from django.contrib import admin
from django.utils.html import format_html
from .models import (
    OfferLetter, Receipt, LoanStatement, DocumentTemplate,
    EmailTemplate, SMSTemplate, AuditLog
)


@admin.register(OfferLetter)
class OfferLetterAdmin(admin.ModelAdmin):
    list_display = [
        'offer_number', 'borrower', 'loan_amount', 'interest_rate',
        'duration_days', 'status', 'valid_until', 'is_expired'
    ]
    list_filter = ['status', 'created_at', 'sent_at', 'signed_at']
    search_fields = [
        'offer_number', 'borrower__username', 'borrower__first_name',
        'borrower__last_name', 'borrower__phone_number'
    ]
    ordering = ['-created_at']
    
    fieldsets = (
        ('Offer Details', {
            'fields': ('offer_number', 'application', 'borrower')
        }),
        ('Loan Terms', {
            'fields': (
                'loan_amount', 'interest_rate', 'duration_days',
                'processing_fee', 'total_amount'
            )
        }),
        ('Terms & Conditions', {
            'fields': ('terms_conditions', 'special_conditions')
        }),
        ('Status', {
            'fields': ('status', 'valid_until', 'is_expired')
        }),
        ('Document', {
            'fields': ('pdf_file',)
        }),
        ('Digital Signature', {
            'fields': ('borrower_signature', 'signed_at'),
            'classes': ('collapse',)
        }),
        ('Timestamps', {
            'fields': ('created_at', 'sent_at')
        }),
    )
    
    readonly_fields = [
        'offer_number', 'created_at', 'is_expired'
    ]
    
    actions = ['mark_as_sent', 'mark_as_expired']
    
    def is_expired(self, obj):
        return obj.is_expired()
    is_expired.boolean = True
    is_expired.short_description = 'Expired'
    
    def mark_as_sent(self, request, queryset):
        for offer in queryset.filter(status='draft'):
            offer.mark_as_sent()
        self.message_user(request, f"{queryset.count()} offer letters marked as sent.")
    mark_as_sent.short_description = "Mark selected offers as sent"
    
    def mark_as_expired(self, request, queryset):
        for offer in queryset.filter(status__in=['draft', 'sent']):
            if offer.is_expired():
                offer.status = 'expired'
                offer.save()
        self.message_user(request, f"Expired offer letters updated.")
    mark_as_expired.short_description = "Mark expired offers"


@admin.register(Receipt)
class ReceiptAdmin(admin.ModelAdmin):
    list_display = [
        'receipt_number', 'borrower', 'loan', 'amount_paid',
        'payment_method', 'payment_date', 'new_balance'
    ]
    list_filter = ['payment_method', 'payment_date']
    search_fields = [
        'receipt_number', 'borrower__username', 'borrower__first_name',
        'borrower__last_name', 'loan__loan_number'
    ]
    ordering = ['-payment_date']
    
    fieldsets = (
        ('Receipt Details', {
            'fields': ('receipt_number', 'repayment', 'loan', 'borrower')
        }),
        ('Payment Information', {
            'fields': ('amount_paid', 'payment_method', 'payment_date')
        }),
        ('Balance Information', {
            'fields': ('previous_balance', 'new_balance')
        }),
        ('Document', {
            'fields': ('pdf_file',)
        }),
        ('Timestamps', {
            'fields': ('created_at',)
        }),
    )
    
    readonly_fields = ['receipt_number', 'payment_date', 'created_at']


@admin.register(LoanStatement)
class LoanStatementAdmin(admin.ModelAdmin):
    list_display = [
        'statement_number', 'borrower', 'loan', 'statement_date',
        'outstanding_balance', 'period_from', 'period_to'
    ]
    list_filter = ['statement_date', 'period_from', 'period_to']
    search_fields = [
        'statement_number', 'borrower__username', 'borrower__first_name',
        'borrower__last_name', 'loan__loan_number'
    ]
    ordering = ['-statement_date']
    
    fieldsets = (
        ('Statement Details', {
            'fields': ('statement_number', 'loan', 'borrower', 'statement_date')
        }),
        ('Period', {
            'fields': ('period_from', 'period_to')
        }),
        ('Loan Summary', {
            'fields': (
                'principal_amount', 'interest_amount', 'total_amount',
                'amount_paid', 'outstanding_balance'
            )
        }),
        ('Document', {
            'fields': ('pdf_file',)
        }),
        ('Timestamps', {
            'fields': ('created_at',)
        }),
    )
    
    readonly_fields = ['statement_number', 'statement_date', 'created_at']


@admin.register(DocumentTemplate)
class DocumentTemplateAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'template_type', 'is_active', 'is_default', 'created_at'
    ]
    list_filter = ['template_type', 'is_active', 'is_default', 'created_at']
    search_fields = ['name', 'description']
    ordering = ['template_type', 'name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'template_type', 'description')
        }),
        ('Template Content', {
            'fields': ('html_template', 'css_styles')
        }),
        ('Configuration', {
            'fields': ('is_active', 'is_default')
        }),
        ('File Upload', {
            'fields': ('template_file',),
            'classes': ('collapse',)
        }),
    )


@admin.register(EmailTemplate)
class EmailTemplateAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'template_type', 'subject', 'is_active', 'is_default'
    ]
    list_filter = ['template_type', 'is_active', 'is_default', 'created_at']
    search_fields = ['name', 'subject', 'html_content']
    ordering = ['template_type', 'name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'template_type', 'subject')
        }),
        ('Template Content', {
            'fields': ('html_content', 'text_content')
        }),
        ('Configuration', {
            'fields': ('is_active', 'is_default')
        }),
    )


@admin.register(SMSTemplate)
class SMSTemplateAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'template_type', 'is_active', 'is_default', 'created_at'
    ]
    list_filter = ['template_type', 'is_active', 'is_default', 'created_at']
    search_fields = ['name', 'message_template']
    ordering = ['template_type', 'name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'template_type')
        }),
        ('Message Template', {
            'fields': ('message_template',)
        }),
        ('Configuration', {
            'fields': ('is_active', 'is_default')
        }),
    )


@admin.register(AuditLog)
class AuditLogAdmin(admin.ModelAdmin):
    list_display = ('user', 'action', 'model_name', 'object_id', 'created_at')
    list_filter = ('action', 'model_name', 'created_at')
    search_fields = ('user__email', 'user__phone_number', 'description', 'object_id')
    readonly_fields = ('created_at', 'ip_address', 'user_agent')
    ordering = ('-created_at',)

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser
