"""
Django Admin Configuration for Notifications Application

This module configures the Django admin interface for notification
management, channel configuration, and delivery monitoring.
"""

from django.contrib import admin
from django.utils import timezone
from django.utils.html import format_html
from apps.notifications.models import (
    NotificationChannel, NotificationTemplate, Notification, NotificationRule
)


@admin.register(NotificationChannel)
class NotificationChannelAdmin(admin.ModelAdmin):
    """
    Admin interface for NotificationChannel model.
    
    Provides management of notification delivery channels including
    configuration, rate limiting, and status monitoring.
    """
    
    # List display configuration
    list_display = [
        'name', 'channel_type', 'is_active', 'rate_limit',
        'get_recent_deliveries', 'created_by', 'created_at'
    ]
    
    # List filtering options
    list_filter = [
        'channel_type', 'is_active', 'created_at', 'created_by'
    ]
    
    # Search functionality
    search_fields = [
        'name', 'channel_type'
    ]
    
    # Field organization
    fieldsets = (
        ('Channel Information', {
            'fields': ('name', 'channel_type', 'is_active')
        }),
        ('Configuration', {
            'fields': ('configuration',),
            'description': 'Channel-specific configuration parameters (JSON format)'
        }),
        ('Delivery Settings', {
            'fields': ('rate_limit', 'retry_attempts', 'timeout_seconds')
        }),
        ('Metadata', {
            'fields': ('created_by',),
            'classes': ('collapse',)
        })
    )
    
    # Read-only fields
    readonly_fields = ['created_at', 'updated_at']
    
    # Ordering
    ordering = ['channel_type', 'name']
    
    def get_recent_deliveries(self, obj):
        """Get recent delivery statistics for this channel."""
        from datetime import timedelta
        
        # Get notifications from the last 24 hours
        recent_time = timezone.now() - timedelta(hours=24)
        recent_notifications = obj.notifications.filter(created_at__gte=recent_time)
        
        total = recent_notifications.count()
        sent = recent_notifications.filter(status='completed').count()
        failed = recent_notifications.filter(status='failed').count()
        
        if total > 0:
            success_rate = (sent / total) * 100
            color = 'green' if success_rate > 90 else 'orange' if success_rate > 70 else 'red'
            
            return format_html(
                '<span style="color: {};">{}/{} sent<br/>({:.1f}%)</span>',
                color,
                sent,
                total,
                success_rate
            )
        return format_html('<span style="color: gray;">No recent activity</span>')
    
    get_recent_deliveries.short_description = 'Recent Deliveries (24h)'
    
    def get_queryset(self, request):
        """Optimize queryset with select_related."""
        return super().get_queryset(request).select_related('created_by')


@admin.register(NotificationTemplate)
class NotificationTemplateAdmin(admin.ModelAdmin):
    """
    Admin interface for NotificationTemplate model.
    
    Provides management of notification message templates including
    content editing, variable management, and compatibility settings.
    """
    
    # List display configuration
    list_display = [
        'name', 'template_type', 'is_active', 'get_usage_count',
        'get_compatible_channels', 'created_at'
    ]
    
    # List filtering options
    list_filter = [
        'template_type', 'is_active', 'created_at'
    ]
    
    # Search functionality
    search_fields = [
        'name', 'template_type', 'subject_template', 'message_template'
    ]
    
    # Field organization
    fieldsets = (
        ('Template Information', {
            'fields': ('name', 'template_type', 'is_active')
        }),
        ('Message Content', {
            'fields': ('subject_template', 'message_template')
        }),
        ('Template Configuration', {
            'fields': ('variables', 'channel_types'),
            'description': 'Available variables and compatible channel types (JSON format)'
        })
    )
    
    # Read-only fields
    readonly_fields = ['created_at', 'updated_at']
    
    # Ordering
    ordering = ['template_type', 'name']
    
    def get_usage_count(self, obj):
        """Get the number of notifications using this template."""
        count = obj.notifications.count()
        recent_count = obj.notifications.filter(
            created_at__gte=timezone.now() - timezone.timedelta(days=7)
        ).count()
        
        if count > 0:
            return format_html(
                '{} total<br/><small>({} this week)</small>',
                count,
                recent_count
            )
        return format_html('<span style="color: gray;">Not used</span>')
    
    get_usage_count.short_description = 'Usage'
    
    def get_compatible_channels(self, obj):
        """Display compatible channel types."""
        if obj.channel_types:
            channel_list = ', '.join(obj.channel_types)
            return format_html('<span title="{}">{}</span>', channel_list, channel_list[:30] + '...' if len(channel_list) > 30 else channel_list)
        return format_html('<span style="color: gray;">All channels</span>')
    
    get_compatible_channels.short_description = 'Compatible Channels'


@admin.register(Notification)
class NotificationAdmin(admin.ModelAdmin):
    """
    Admin interface for Notification model.
    
    Provides detailed monitoring of individual notifications including
    delivery status, error tracking, and retry management.
    """
    
    # List display configuration
    list_display = [
        'get_notification_info', 'channel', 'recipient', 'template',
        'status', 'scheduled_at', 'sent_at', 'delivery_attempts'
    ]
    
    # List filtering options
    list_filter = [
        'status', 'channel', 'template', 'scheduled_at', 'sent_at'
    ]
    
    # Search functionality
    search_fields = [
        'recipient', 'subject', 'message', 'channel__name', 'template__name'
    ]
    
    # Field organization
    fieldsets = (
        ('Notification Details', {
            'fields': ('channel', 'template', 'recipient', 'status')
        }),
        ('Message Content', {
            'fields': ('subject', 'message')
        }),
        ('Scheduling', {
            'fields': ('scheduled_at', 'sent_at')
        }),
        ('Delivery Tracking', {
            'fields': ('delivery_attempts', 'error_message', 'external_id')
        }),
        ('Template Context', {
            'fields': ('context_data',),
            'classes': ('collapse',)
        })
    )
    
    # Read-only fields
    readonly_fields = [
        'created_at', 'updated_at', 'sent_at', 'delivery_attempts'
    ]
    
    # Ordering
    ordering = ['-scheduled_at']
    
    def get_notification_info(self, obj):
        """Get formatted notification information."""
        status_color = {
            'pending': 'orange',
            'processing': 'blue',
            'completed': 'green',
            'failed': 'red',
            'cancelled': 'gray',
        }.get(obj.status, 'black')
        
        subject_preview = obj.subject[:30] + '...' if len(obj.subject) > 30 else obj.subject
        
        return format_html(
            '<strong>{}</strong><br/>'
            '<span style="color: {};">{}</span>',
            subject_preview or obj.message[:30] + '...',
            status_color,
            obj.status.title()
        )
    
    get_notification_info.short_description = 'Notification'
    get_notification_info.admin_order_field = 'subject'
    
    def get_queryset(self, request):
        """Optimize queryset with select_related."""
        return super().get_queryset(request).select_related('channel', 'template')
    
    # Custom actions
    actions = ['retry_failed_notifications', 'mark_as_cancelled']
    
    def retry_failed_notifications(self, request, queryset):
        """Custom action to retry failed notifications."""
        failed_notifications = queryset.filter(status='failed')
        retry_count = 0
        
        for notification in failed_notifications:
            if notification.can_retry():
                notification.status = 'pending'
                notification.save()
                retry_count += 1
        
        self.message_user(
            request,
            f"Queued {retry_count} notifications for retry."
        )
    
    retry_failed_notifications.short_description = "Retry failed notifications"
    
    def mark_as_cancelled(self, request, queryset):
        """Custom action to cancel pending notifications."""
        pending_notifications = queryset.filter(status='pending')
        cancelled_count = pending_notifications.update(status='cancelled')
        
        self.message_user(
            request,
            f"Cancelled {cancelled_count} pending notifications."
        )
    
    mark_as_cancelled.short_description = "Cancel pending notifications"


@admin.register(NotificationRule)
class NotificationRuleAdmin(admin.ModelAdmin):
    """
    Admin interface for NotificationRule model.
    
    Provides management of automatic notification rules including
    event triggering, conditions, and throttling configuration.
    """
    
    # List display configuration
    list_display = [
        'name', 'event_type', 'channel', 'template', 'is_active',
        'throttle_minutes', 'get_trigger_count', 'last_triggered'
    ]
    
    # List filtering options
    list_filter = [
        'event_type', 'is_active', 'channel', 'template', 'last_triggered'
    ]
    
    # Search functionality
    search_fields = [
        'name', 'event_type', 'channel__name', 'template__name'
    ]
    
    # Field organization
    fieldsets = (
        ('Rule Information', {
            'fields': ('name', 'event_type', 'is_active', 'priority')
        }),
        ('Notification Configuration', {
            'fields': ('channel', 'template')
        }),
        ('Triggering Conditions', {
            'fields': ('conditions',),
            'description': 'Additional conditions for rule triggering (JSON format)'
        }),
        ('Throttling', {
            'fields': ('throttle_minutes', 'last_triggered')
        })
    )
    
    # Read-only fields
    readonly_fields = ['created_at', 'updated_at', 'last_triggered']
    
    # Ordering
    ordering = ['-priority', 'name']
    
    def get_trigger_count(self, obj):
        """Get the number of times this rule has been triggered."""
        # This would require additional tracking in the model
        # For now, we'll show a placeholder
        if obj.last_triggered:
            return format_html(
                '<span style="color: green;">Active</span><br/>'
                '<small>Last: {}</small>',
                obj.last_triggered.strftime('%m/%d %H:%M')
            )
        return format_html('<span style="color: gray;">Never triggered</span>')
    
    get_trigger_count.short_description = 'Trigger Status'
    
    def get_queryset(self, request):
        """Optimize queryset with select_related."""
        return super().get_queryset(request).select_related('channel', 'template')
    
    # Custom actions
    actions = ['test_notification_rule']
    
    def test_notification_rule(self, request, queryset):
        """Custom action to test notification rules."""
        from .tasks import send_notification_via_rule
        
        test_count = 0
        for rule in queryset.filter(is_active=True):
            # Send test notification with dummy context
            test_context = {
                'test_mode': True,
                'rule_name': rule.name,
                'timestamp': timezone.now().isoformat()
            }
            
            try:
                send_notification_via_rule.delay(rule.event_type, test_context)
                test_count += 1
            except Exception as e:
                self.message_user(
                    request,
                    f"Failed to test rule {rule.name}: {e}",
                    level='ERROR'
                )
        
        if test_count > 0:
            self.message_user(
                request,
                f"Queued {test_count} test notifications."
            )
    
    test_notification_rule.short_description = "Send test notifications"
