from django.contrib import admin
from django.utils.html import format_html
from .models import (
    LoanScoring, Notification, SystemSettings, 
    ReportTemplate, GeneratedReport
)


@admin.register(LoanScoring)
class LoanScoringAdmin(admin.ModelAdmin):
    list_display = [
        'user', 'total_score', 'risk_level', 'credit_limit', 
        'is_eligible', 'calculated_at'
    ]
    list_filter = ['risk_level', 'is_eligible', 'calculated_at']
    search_fields = [
        'user__username', 'user__first_name', 'user__last_name',
        'user__phone_number'
    ]
    ordering = ['-calculated_at']
    
    fieldsets = (
        ('User Information', {
            'fields': ('user',)
        }),
        ('Scoring Factors', {
            'fields': (
                'repayment_history_score', 'income_score', 
                'rollover_frequency_score', 'employment_stability_score'
            )
        }),
        ('Results', {
            'fields': ('total_score', 'credit_limit', 'risk_level', 'is_eligible')
        }),
        ('Timestamps', {
            'fields': ('calculated_at', 'updated_at')
        }),
    )
    
    readonly_fields = ['calculated_at', 'updated_at']
    
    actions = ['recalculate_scores']
    
    def recalculate_scores(self, request, queryset):
        for scoring in queryset:
            scoring.calculate_score()
        self.message_user(request, f"{queryset.count()} credit scores recalculated.")
    recalculate_scores.short_description = "Recalculate selected credit scores"


@admin.register(Notification)
class NotificationAdmin(admin.ModelAdmin):
    list_display = [
        'user', 'notification_type', 'title', 'channel', 
        'is_sent', 'created_at'
    ]
    list_filter = [
        'notification_type', 'channel', 'is_sent', 'created_at'
    ]
    search_fields = [
        'user__username', 'user__first_name', 'user__last_name',
        'title', 'message'
    ]
    ordering = ['-created_at']
    
    fieldsets = (
        ('Notification Details', {
            'fields': ('user', 'notification_type', 'title', 'message')
        }),
        ('Delivery', {
            'fields': ('channel', 'is_sent', 'sent_at')
        }),
        ('Related Objects', {
            'fields': ('related_loan', 'related_application'),
            'classes': ('collapse',)
        }),
        ('Timestamps', {
            'fields': ('created_at',)
        }),
    )
    
    readonly_fields = ['created_at']
    
    actions = ['mark_as_sent']
    
    def mark_as_sent(self, request, queryset):
        for notification in queryset.filter(is_sent=False):
            notification.mark_as_sent()
        self.message_user(request, f"{queryset.count()} notifications marked as sent.")
    mark_as_sent.short_description = "Mark selected notifications as sent"


@admin.register(SystemSettings)
class SystemSettingsAdmin(admin.ModelAdmin):
    list_display = [
        'default_interest_rate', 'default_processing_fee', 
        'auto_approval_enabled', 'email_notifications_enabled'
    ]
    
    fieldsets = (
        ('Loan Settings', {
            'fields': (
                'default_interest_rate', 'default_processing_fee', 
                'default_late_penalty'
            )
        }),
        ('Rollover Settings', {
            'fields': (
                'rollover_fee_percentage', 'max_rollover_days', 
                'max_rollover_count'
            )
        }),
        ('Auto-Approval Settings', {
            'fields': (
                'auto_approval_enabled', 'auto_approval_min_score',
                'auto_approval_max_amount'
            )
        }),
        ('Notification Settings', {
            'fields': (
                'email_notifications_enabled', 'sms_notifications_enabled'
            )
        }),
        ('M-Pesa Settings', {
            'fields': (
                'mpesa_business_shortcode', 'mpesa_passkey', 'mpesa_environment'
            ),
            'classes': ('collapse',)
        }),
    )
    
    def has_add_permission(self, request):
        # Only allow one system settings instance
        return not SystemSettings.objects.exists()
    
    def has_delete_permission(self, request, obj=None):
        return False


@admin.register(ReportTemplate)
class ReportTemplateAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'report_type', 'is_active', 'created_at'
    ]
    list_filter = ['report_type', 'is_active', 'created_at']
    search_fields = ['name', 'description']
    ordering = ['report_type', 'name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'report_type', 'description')
        }),
        ('Template Configuration', {
            'fields': ('template_file', 'is_active')
        }),
    )


@admin.register(GeneratedReport)
class GeneratedReportAdmin(admin.ModelAdmin):
    list_display = [
        'report_name', 'report_type', 'format', 'generated_by',
        'file_size', 'generated_at'
    ]
    list_filter = ['report_type', 'format', 'generated_at']
    search_fields = [
        'report_name', 'report_type', 'generated_by__username',
        'generated_by__first_name', 'generated_by__last_name'
    ]
    ordering = ['-generated_at']
    
    fieldsets = (
        ('Report Details', {
            'fields': ('report_name', 'report_type', 'format')
        }),
        ('File Information', {
            'fields': ('file_path', 'file_size')
        }),
        ('Generation Details', {
            'fields': ('generated_by', 'parameters')
        }),
        ('Timestamps', {
            'fields': ('generated_at',)
        }),
    )
    
    readonly_fields = ['generated_at']
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False

# Enhanced models admin configurations
from .enhanced_models import CustomerRequest, RegistrationFee, RegistrationFeePayment, ReportSchedule, ReportExecution


@admin.register(CustomerRequest)
class CustomerRequestAdmin(admin.ModelAdmin):
    list_display = ['request_number', 'customer_name', 'request_type', 'priority', 'status', 'assigned_to', 'created_at']
    list_filter = ['status', 'request_type', 'priority', 'created_at']
    search_fields = ['request_number', 'customer__first_name', 'customer__last_name', 'subject']
    readonly_fields = ['request_number', 'created_at', 'updated_at']
    raw_id_fields = ['customer', 'assigned_to', 'resolved_by', 'related_loan', 'related_application']
    
    fieldsets = (
        ('Request Information', {
            'fields': ('request_number', 'customer', 'request_type', 'subject', 'description', 'priority')
        }),
        ('Status & Assignment', {
            'fields': ('status', 'assigned_to', 'resolution_notes', 'resolved_by', 'resolved_at')
        }),
        ('Related Objects', {
            'fields': ('related_loan', 'related_application'),
            'classes': ('collapse',)
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def customer_name(self, obj):
        return obj.customer.get_full_name()
    customer_name.short_description = 'Customer'
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('customer', 'assigned_to', 'resolved_by')


@admin.register(RegistrationFee)
class RegistrationFeeAdmin(admin.ModelAdmin):
    list_display = ['fee_name', 'product_type', 'amount_display', 'is_active', 'created_at']
    list_filter = ['product_type', 'is_active', 'created_at']
    search_fields = ['fee_name', 'description']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('Fee Information', {
            'fields': ('product_type', 'fee_name', 'amount', 'description')
        }),
        ('Status & Validity', {
            'fields': ('is_active', 'effective_from', 'effective_to')
        }),
        ('Audit', {
            'fields': ('created_by', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def amount_display(self, obj):
        return format_html('<strong>KES {:,.2f}</strong>', obj.amount)
    amount_display.short_description = 'Amount'
    
    def save_model(self, request, obj, form, change):
        if not change:  # Creating new object
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(RegistrationFeePayment)
class RegistrationFeePaymentAdmin(admin.ModelAdmin):
    list_display = ['receipt_number', 'customer_name', 'fee_name', 'amount_display', 'payment_method', 'payment_date']
    list_filter = ['payment_method', 'payment_date', 'registration_fee__product_type']
    search_fields = ['receipt_number', 'customer__first_name', 'customer__last_name', 'transaction_reference']
    readonly_fields = ['receipt_number', 'created_at']
    raw_id_fields = ['customer', 'processed_by', 'related_loan', 'related_application']
    date_hierarchy = 'payment_date'
    
    fieldsets = (
        ('Payment Information', {
            'fields': ('receipt_number', 'customer', 'registration_fee', 'amount_paid')
        }),
        ('Payment Details', {
            'fields': ('payment_method', 'payment_date', 'transaction_reference', 'payment_notes')
        }),
        ('Related Objects', {
            'fields': ('related_loan', 'related_application'),
            'classes': ('collapse',)
        }),
        ('Processing', {
            'fields': ('processed_by', 'created_at'),
            'classes': ('collapse',)
        })
    )
    
    def customer_name(self, obj):
        return obj.customer.get_full_name()
    customer_name.short_description = 'Customer'
    
    def fee_name(self, obj):
        return obj.registration_fee.fee_name
    fee_name.short_description = 'Fee'
    
    def amount_display(self, obj):
        return format_html('<strong>KES {:,.2f}</strong>', obj.amount_paid)
    amount_display.short_description = 'Amount'
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('customer', 'registration_fee', 'processed_by')


@admin.register(ReportSchedule)
class ReportScheduleAdmin(admin.ModelAdmin):
    list_display = ['name', 'report_type', 'frequency', 'is_active', 'next_run', 'last_run']
    list_filter = ['report_type', 'frequency', 'is_active']
    search_fields = ['name']
    readonly_fields = ['created_at']
    filter_horizontal = ['recipients']
    
    fieldsets = (
        ('Schedule Information', {
            'fields': ('name', 'report_type', 'frequency', 'is_active')
        }),
        ('Schedule Timing', {
            'fields': ('next_run', 'last_run')
        }),
        ('Recipients', {
            'fields': ('recipients',)
        }),
        ('Parameters', {
            'fields': ('parameters',),
            'classes': ('collapse',)
        }),
        ('Audit', {
            'fields': ('created_by', 'created_at'),
            'classes': ('collapse',)
        })
    )
    
    def save_model(self, request, obj, form, change):
        if not change:  # Creating new object
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(ReportExecution)
class ReportExecutionAdmin(admin.ModelAdmin):
    list_display = ['report_type', 'status', 'started_at', 'execution_time_display', 'records_processed']
    list_filter = ['status', 'report_type', 'started_at']
    search_fields = ['report_type']
    readonly_fields = ['started_at', 'completed_at', 'execution_time']
    
    fieldsets = (
        ('Execution Information', {
            'fields': ('schedule', 'report_type', 'status')
        }),
        ('Timing', {
            'fields': ('started_at', 'completed_at', 'execution_time')
        }),
        ('Results', {
            'fields': ('records_processed', 'pdf_file', 'excel_file')
        }),
        ('Error Information', {
            'fields': ('error_message',),
            'classes': ('collapse',)
        }),
        ('Parameters', {
            'fields': ('parameters',),
            'classes': ('collapse',)
        })
    )
    
    def execution_time_display(self, obj):
        if obj.execution_time:
            return f"{obj.execution_time:.2f}s"
        return "-"
    execution_time_display.short_description = 'Execution Time'
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('schedule')