"""Django admin configuration for adspots app.

This module provides admin interfaces for:
- Adspot: Managing advertising spots
- Avail: Managing availability windows
- Window: Managing time windows
- AdspotInAvail: Managing adspot placements
- Pending: Managing pending creatives
"""

from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django.urls import reverse
from django.utils.safestring import mark_safe

from .models import Adspot, Avail, Window, AdspotInAvail, Pending


@admin.register(Adspot)
class AdspotAdmin(admin.ModelAdmin):
    """Admin interface for Adspot model."""
    
    list_display = [
        'name',
        'campaign',
        'brand',
        'channel',
        'duration',
        'format',
        'processing_status',
        'is_processed',
        'file_size_display',
        'created_at',
    ]
    
    list_filter = [
        'processing_status',
        'is_processed',
        'format',
        'status',
        'campaign',
        'brand',
        'channel',
        'created_at',
    ]
    
    search_fields = [
        'name',
        'creative_id',
        'filename',
        'campaign__name',
        'brand__name',
        'channel__name',
    ]
    
    readonly_fields = [
        'id',
        'uuid',
        'file_size_display',
        'md5_hash',
        'created_at',
        'updated_at',
        'created_by',
        'updated_by',
        'file_preview',
        'impressions_summary',
    ]
    
    fieldsets = [
        (_('Basic Information'), {
            'fields': [
                'name',
                'creative_id',
                'status',
            ]
        }),
        (_('Relationships'), {
            'fields': [
                'campaign',
                'brand',
                'channel',
            ]
        }),
        (_('File Information'), {
            'fields': [
                'original_file',
                'encoded_file',
                'file_preview',
                'filename',
                'file_size_display',
                'md5_hash',
            ]
        }),
        (_('Media Properties'), {
            'fields': [
                'duration',
                'format',
                'resolution',
                'bitrate',
                'frame_rate',
                'audio_codec',
                'video_codec',
            ]
        }),
        (_('Processing'), {
            'fields': [
                'is_processed',
                'processing_status',
                'error_message',
            ]
        }),
        (_('VAST'), {
            'fields': [
                'vast_url',
            ]
        }),
        (_('Analytics'), {
            'fields': [
                'impressions_summary',
            ]
        }),
        (_('System Information'), {
            'fields': [
                'id',
                'uuid',
                'created_at',
                'updated_at',
                'created_by',
                'updated_by',
            ],
            'classes': ['collapse'],
        }),
    ]
    
    def file_size_display(self, obj):
        """Display file size in human readable format."""
        if obj.file_size:
            if obj.file_size < 1024:
                return f"{obj.file_size} B"
            elif obj.file_size < 1024 * 1024:
                return f"{obj.file_size / 1024:.1f} KB"
            elif obj.file_size < 1024 * 1024 * 1024:
                return f"{obj.file_size / (1024 * 1024):.1f} MB"
            else:
                return f"{obj.file_size / (1024 * 1024 * 1024):.1f} GB"
        return "-"
    file_size_display.short_description = _('File Size')
    
    def file_preview(self, obj):
        """Display file preview if available."""
        if obj.original_file:
            if obj.format in ['mp4', 'webm', 'mov']:
                return format_html(
                    '<video width="320" height="240" controls>'
                    '<source src="{}" type="video/{}">'
                    'Your browser does not support the video tag.'
                    '</video>',
                    obj.original_file.url,
                    obj.format
                )
            elif obj.format in ['mp3', 'wav', 'aac']:
                return format_html(
                    '<audio controls>'
                    '<source src="{}" type="audio/{}">'
                    'Your browser does not support the audio element.'
                    '</audio>',
                    obj.original_file.url,
                    obj.format
                )
            else:
                return format_html(
                    '<a href="{}" target="_blank">Download File</a>',
                    obj.original_file.url
                )
        return "-"
    file_preview.short_description = _('File Preview')
    
    def impressions_summary(self, obj):
        """Display impressions summary."""
        stats = obj.get_impressions()
        return format_html(
            '<strong>Total Requests:</strong> {}<br>'
            '<strong>Successful Impressions:</strong> {}<br>'
            '<strong>Completion Rate:</strong> {}',
            stats['total_requests'],
            stats['successful_impressions'],
            stats['completion_rate']
        )
    impressions_summary.short_description = _('Impressions Summary')
    
    actions = ['mark_as_processed', 'mark_as_pending', 'reprocess_files']
    
    def mark_as_processed(self, request, queryset):
        """Mark selected adspots as processed."""
        updated = queryset.update(
            is_processed=True,
            processing_status='completed'
        )
        self.message_user(
            request,
            f"{updated} adspot(s) marked as processed."
        )
    mark_as_processed.short_description = _('Mark selected adspots as processed')
    
    def mark_as_pending(self, request, queryset):
        """Mark selected adspots as pending."""
        updated = queryset.update(
            is_processed=False,
            processing_status='pending'
        )
        self.message_user(
            request,
            f"{updated} adspot(s) marked as pending."
        )
    mark_as_pending.short_description = _('Mark selected adspots as pending')
    
    def reprocess_files(self, request, queryset):
        """Reprocess selected adspot files."""
        updated = queryset.update(
            is_processed=False,
            processing_status='pending',
            error_message=None
        )
        self.message_user(
            request,
            f"{updated} adspot(s) queued for reprocessing."
        )
    reprocess_files.short_description = _('Reprocess selected adspot files')


class AdspotInAvailInline(admin.TabularInline):
    """Inline admin for AdspotInAvail."""
    model = AdspotInAvail
    extra = 0
    fields = ['adspot', 'position_in_avail', 'traffic_id']
    autocomplete_fields = ['adspot']


@admin.register(Avail)
class AvailAdmin(admin.ModelAdmin):
    """Admin interface for Avail model."""
    
    list_display = [
        'id',
        'window',
        'avail_start',
        'avail_in_window',
        'adspot_count',
        'created_at',
    ]
    
    list_filter = [
        'window',
        'created_at',
    ]
    
    search_fields = [
        'avail_start',
        'avail_in_window',
        'window__window_start',
    ]
    
    readonly_fields = [
        'id',
        'uuid',
        'created_at',
        'updated_at',
        'created_by',
        'updated_by',
        'adspot_count',
    ]
    
    fieldsets = [
        (_('Basic Information'), {
            'fields': [
                'window',
                'avail_start',
                'avail_in_window',
            ]
        }),
        (_('Statistics'), {
            'fields': [
                'adspot_count',
            ]
        }),
        (_('System Information'), {
            'fields': [
                'id',
                'uuid',
                'created_at',
                'updated_at',
                'created_by',
                'updated_by',
            ],
            'classes': ['collapse'],
        }),
    ]
    
    inlines = [AdspotInAvailInline]
    
    def adspot_count(self, obj):
        """Display count of adspots in this avail."""
        return obj.adspot_placements.count()
    adspot_count.short_description = _('Adspot Count')


@admin.register(Window)
class WindowAdmin(admin.ModelAdmin):
    """Admin interface for Window model."""
    
    list_display = [
        'id',
        'playlist',
        'window_start',
        'window_end',
        'window_duration',
        'avail_count',
        'created_at',
    ]
    
    list_filter = [
        'playlist',
        'created_at',
    ]
    
    search_fields = [
        'window_start',
        'window_end',
        'playlist__name',
    ]
    
    readonly_fields = [
        'id',
        'uuid',
        'created_at',
        'updated_at',
        'created_by',
        'updated_by',
        'avail_count',
    ]
    
    fieldsets = [
        (_('Basic Information'), {
            'fields': [
                'playlist',
                'window_start',
                'window_end',
                'window_duration',
            ]
        }),
        (_('Statistics'), {
            'fields': [
                'avail_count',
            ]
        }),
        (_('System Information'), {
            'fields': [
                'id',
                'uuid',
                'created_at',
                'updated_at',
                'created_by',
                'updated_by',
            ],
            'classes': ['collapse'],
        }),
    ]
    
    def avail_count(self, obj):
        """Display count of avails in this window."""
        return obj.avails.count()
    avail_count.short_description = _('Avail Count')


@admin.register(AdspotInAvail)
class AdspotInAvailAdmin(admin.ModelAdmin):
    """Admin interface for AdspotInAvail model."""
    
    list_display = [
        'id',
        'avail',
        'adspot',
        'position_in_avail',
        'traffic_id',
        'created_at',
    ]
    
    list_filter = [
        'avail__window',
        'adspot__campaign',
        'adspot__brand',
        'created_at',
    ]
    
    search_fields = [
        'adspot__name',
        'adspot__creative_id',
        'traffic_id',
    ]
    
    autocomplete_fields = ['avail', 'adspot']
    
    readonly_fields = [
        'id',
        'uuid',
        'created_at',
        'updated_at',
        'created_by',
        'updated_by',
    ]
    
    fieldsets = [
        (_('Placement Information'), {
            'fields': [
                'avail',
                'adspot',
                'position_in_avail',
                'traffic_id',
            ]
        }),
        (_('System Information'), {
            'fields': [
                'id',
                'uuid',
                'created_at',
                'updated_at',
                'created_by',
                'updated_by',
            ],
            'classes': ['collapse'],
        }),
    ]


@admin.register(Pending)
class PendingAdmin(admin.ModelAdmin):
    """Admin interface for Pending model."""
    
    list_display = [
        'creative_id',
        'url_display',
        'duration',
        'status',
        'created_at',
    ]
    
    list_filter = [
        'status',
        'created_at',
    ]
    
    search_fields = [
        'creative_id',
        'url',
    ]
    
    readonly_fields = [
        'id',
        'uuid',
        'created_at',
        'updated_at',
        'created_by',
        'updated_by',
    ]
    
    fieldsets = [
        (_('Creative Information'), {
            'fields': [
                'creative_id',
                'url',
                'duration',
                'status',
                'error_message',
            ]
        }),
        (_('System Information'), {
            'fields': [
                'id',
                'uuid',
                'created_at',
                'updated_at',
                'created_by',
                'updated_by',
            ],
            'classes': ['collapse'],
        }),
    ]
    
    def url_display(self, obj):
        """Display URL with link."""
        if obj.url:
            return format_html(
                '<a href="{}" target="_blank">{}</a>',
                obj.url,
                obj.url[:50] + '...' if len(obj.url) > 50 else obj.url
            )
        return "-"
    url_display.short_description = _('URL')
    
    actions = ['approve_pending', 'reject_pending', 'reset_to_pending']
    
    def approve_pending(self, request, queryset):
        """Approve selected pending creatives."""
        updated = queryset.update(status='approved')
        self.message_user(
            request,
            f"{updated} pending creative(s) approved."
        )
    approve_pending.short_description = _('Approve selected pending creatives')
    
    def reject_pending(self, request, queryset):
        """Reject selected pending creatives."""
        updated = queryset.update(status='rejected')
        self.message_user(
            request,
            f"{updated} pending creative(s) rejected."
        )
    reject_pending.short_description = _('Reject selected pending creatives')
    
    def reset_to_pending(self, request, queryset):
        """Reset selected items to pending status."""
        updated = queryset.update(
            status='pending',
            error_message=None
        )
        self.message_user(
            request,
            f"{updated} item(s) reset to pending status."
        )
    reset_to_pending.short_description = _('Reset selected items to pending')