from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from .models import Codec, Zone, Channel, ChannelZone, Jingle, Show, EPGEntry


@admin.register(Codec)
class CodecAdmin(admin.ModelAdmin):
    """
    Admin interface for managing video/audio codecs.
    
    Provides comprehensive management of codec configurations
    with filtering, searching, and validation capabilities.
    """
    list_display = [
        'name', 
        'codec_type', 
        'mime_type', 
        'bitrate_range_display', 
        'is_active_display',
        'created_at'
    ]
    list_filter = [
        'codec_type', 
        'is_active', 
        'created_at'
    ]
    search_fields = [
        'name', 
        'description', 
        'mime_type'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'codec_type', 'description')
        }),
        ('Technical Details', {
            'fields': ('mime_type', 'bitrate_min', 'bitrate_max')
        }),
        ('Status', {
            'fields': ('is_active',)
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def bitrate_range_display(self, obj):
        """
        Display bitrate range in a formatted way.
        """
        if obj.bitrate_min and obj.bitrate_max:
            return f"{obj.bitrate_min} - {obj.bitrate_max} kbps"
        elif obj.bitrate_min:
            return f"≥ {obj.bitrate_min} kbps"
        elif obj.bitrate_max:
            return f"≤ {obj.bitrate_max} kbps"
        return "Not specified"
    bitrate_range_display.short_description = 'Bitrate Range'
    
    def is_active_display(self, obj):
        """
        Display active status with colored indicator.
        """
        if obj.is_active:
            return format_html(
                '<span style="color: green;">✓ Active</span>'
            )
        return format_html(
            '<span style="color: red;">✗ Inactive</span>'
        )
    is_active_display.short_description = 'Status'


@admin.register(Zone)
class ZoneAdmin(admin.ModelAdmin):
    """
    Admin interface for managing distribution zones.
    
    Provides management of geographical and logical distribution zones
    with timezone and activity status tracking.
    """
    list_display = [
        'name', 
        'code', 
        'timezone', 
        'channels_count', 
        'is_active_display',
        'created_at'
    ]
    list_filter = [
        'is_active', 
        'timezone', 
        'created_at'
    ]
    search_fields = [
        'name', 
        'code', 
        'description'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'code', 'description')
        }),
        ('Configuration', {
            'fields': ('timezone',)
        }),
        ('Status', {
            'fields': ('is_active',)
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def channels_count(self, obj):
        """
        Display the number of channels in this zone.
        """
        count = obj.zone_channels.filter(is_active=True).count()
        return f"{count} channels"
    channels_count.short_description = 'Active Channels'
    
    def is_active_display(self, obj):
        """
        Display active status with colored indicator.
        """
        if obj.is_active:
            return format_html(
                '<span style="color: green;">✓ Active</span>'
            )
        return format_html(
            '<span style="color: red;">✗ Inactive</span>'
        )
    is_active_display.short_description = 'Status'


class ChannelZoneInline(admin.TabularInline):
    """
    Inline admin for managing channel-zone configurations.
    
    Allows editing zone distributions directly from the channel admin.
    """
    model = ChannelZone
    extra = 1
    fields = [
        'zone', 
        'video_codec', 
        'audio_codec', 
        'container_format',
        'bitrate', 
        'resolution_width', 
        'resolution_height',
        'frame_rate', 
        'is_active'
    ]
    

class JingleInline(admin.TabularInline):
    """
    Inline admin for managing channel jingles.
    
    Allows editing jingles directly from the channel admin.
    """
    model = Jingle
    extra = 0
    fields = [
        'name', 
        'jingle_type', 
        'duration', 
        'priority', 
        'is_active'
    ]
    readonly_fields = ['duration']


@admin.register(Channel)
class ChannelAdmin(admin.ModelAdmin):
    """
    Admin interface for managing TV channels.
    
    Comprehensive management of channels with inline editing
    of zone configurations and jingles.
    """
    list_display = [
        'name', 
        'call_sign', 
        'channel_type', 
        'logo_display',
        'zones_count', 
        'jingles_count',
        'content_rating',
        'is_active_display',
        'created_at'
    ]
    list_filter = [
        'channel_type', 
        'content_rating', 
        'language', 
        'country',
        'is_active', 
        'is_hd', 
        'is_4k',
        'created_at'
    ]
    search_fields = [
        'name', 
        'call_sign', 
        'description'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    prepopulated_fields = {
        'slug': ('name',)
    }
    inlines = [
        ChannelZoneInline, 
        JingleInline
    ]
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'slug', 'call_sign', 'description')
        }),
        ('Technical Details', {
            'fields': (
                'channel_number', 'channel_type', 
                'is_hd', 'is_4k'
            )
        }),
        ('Content Information', {
            'fields': (
                'content_rating', 'language', 'country'
            )
        }),
        ('Media', {
            'fields': ('logo', 'website')
        }),
        ('Status & Dates', {
            'fields': ('is_active', 'launch_date')
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def logo_display(self, obj):
        """
        Display channel logo as thumbnail in admin list.
        """
        if obj.logo:
            return format_html(
                '<img src="{}" width="30" height="30" style="border-radius: 3px;" />',
                obj.logo.url
            )
        return "No logo"
    logo_display.short_description = 'Logo'
    
    def zones_count(self, obj):
        """
        Display the number of active zones for this channel.
        """
        return obj.active_zones_count
    zones_count.short_description = 'Active Zones'
    
    def jingles_count(self, obj):
        """
        Display the number of jingles for this channel.
        """
        return obj.total_jingles_count
    jingles_count.short_description = 'Jingles'
    
    def is_active_display(self, obj):
        """
        Display active status with colored indicator.
        """
        if obj.is_active:
            return format_html(
                '<span style="color: green;">✓ Active</span>'
            )
        return format_html(
            '<span style="color: red;">✗ Inactive</span>'
        )
    is_active_display.short_description = 'Status'


@admin.register(ChannelZone)
class ChannelZoneAdmin(admin.ModelAdmin):
    """
    Admin interface for managing channel-zone configurations.
    
    Provides detailed management of how channels are distributed
    across different zones with specific codec configurations.
    """
    list_display = [
        'channel', 
        'zone', 
        'video_codec', 
        'audio_codec',
        'resolution_display_admin', 
        'bitrate', 
        'is_active_display',
        'start_date'
    ]
    list_filter = [
        'is_active', 
        'video_codec', 
        'audio_codec',
        'start_date'
    ]
    search_fields = [
        'channel__name', 
        'zone__name'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    fieldsets = (
        ('Channel & Zone', {
            'fields': ('channel', 'zone')
        }),
        ('Codec Configuration', {
            'fields': (
                'video_codec', 'audio_codec', 'container_format'
            )
        }),
        ('Technical Parameters', {
            'fields': (
                'bitrate', 'resolution_width', 'resolution_height',
                'frame_rate'
            )
        }),
        ('Schedule', {
            'fields': ('start_date', 'end_date', 'is_active')
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def resolution_display_admin(self, obj):
        """
        Display resolution in admin list.
        """
        return obj.resolution_display
    resolution_display_admin.short_description = 'Resolution'
    
    def is_active_display(self, obj):
        """
        Display active status with colored indicator.
        """
        if obj.is_active:
            return format_html(
                '<span style="color: green;">✓ Active</span>'
            )
        return format_html(
            '<span style="color: red;">✗ Inactive</span>'
        )
    is_active_display.short_description = 'Status'


@admin.register(Jingle)
class JingleAdmin(admin.ModelAdmin):
    """
    Admin interface for managing channel jingles.
    
    Provides management of audio/video jingles used for
    ad break identification and station branding.
    """
    list_display = [
        'name', 
        'channel', 
        'jingle_type', 
        'duration',
        'files_display', 
        'priority', 
        'is_active_display',
        'created_at'
    ]
    list_filter = [
        'jingle_type', 
        'channel', 
        'is_active',
        'priority', 
        'created_at'
    ]
    search_fields = [
        'name', 
        'channel__name', 
        'description'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'channel', 'jingle_type', 'description')
        }),
        ('Media Files', {
            'fields': ('audio_file', 'video_file', 'duration')
        }),
        ('Configuration', {
            'fields': ('priority', 'is_active')
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def files_display(self, obj):
        """
        Display which files are available for this jingle.
        """
        files = []
        if obj.audio_file:
            files.append('Audio')
        if obj.video_file:
            files.append('Video')
        return ', '.join(files) if files else 'No files'
    files_display.short_description = 'Available Files'
    
    def is_active_display(self, obj):
        """
        Display active status with colored indicator.
        """
        if obj.is_active:
            return format_html(
                '<span style="color: green;">✓ Active</span>'
            )
        return format_html(
            '<span style="color: red;">✗ Inactive</span>'
        )
    is_active_display.short_description = 'Status'


@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
    """
    Admin interface for managing TV shows.
    
    Comprehensive management of show metadata and content information
    for EPG scheduling and program guide generation.
    """
    list_display = [
        'title', 
        'show_type', 
        'content_rating',
        'year', 
        'language', 
        'poster_display',
        'epg_entries_count',
        'is_active_display',
        'created_at'
    ]
    list_filter = [
        'show_type', 
        'content_rating', 
        'language',
        'country', 
        'year', 
        'is_active',
        'created_at'
    ]
    search_fields = [
        'title', 
        'description', 
        'short_description',
        'cast', 
        'director', 
        'producer'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    prepopulated_fields = {
        'slug': ('title',)
    }
    fieldsets = (
        ('Basic Information', {
            'fields': ('title', 'slug', 'show_type', 'description', 'short_description')
        }),
        ('Content Details', {
            'fields': (
                'content_rating', 'language', 'country', 
                'year', 'duration', 'genre'
            )
        }),
        ('Production Information', {
            'fields': ('cast', 'director', 'producer', 'imdb_id')
        }),
        ('Media', {
            'fields': ('poster', 'thumbnail')
        }),
        ('Status', {
            'fields': ('is_active',)
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def poster_display(self, obj):
        """
        Display show poster as thumbnail in admin list.
        """
        if obj.poster:
            return format_html(
                '<img src="{}" width="30" height="40" style="border-radius: 3px;" />',
                obj.poster.url
            )
        return "No poster"
    poster_display.short_description = 'Poster'
    
    def epg_entries_count(self, obj):
        """
        Display the number of EPG entries for this show.
        """
        count = obj.epg_entries.count()
        return f"{count} entries"
    epg_entries_count.short_description = 'EPG Entries'
    
    def is_active_display(self, obj):
        """
        Display active status with colored indicator.
        """
        if obj.is_active:
            return format_html(
                '<span style="color: green;">✓ Active</span>'
            )
        return format_html(
            '<span style="color: red;">✗ Inactive</span>'
        )
    is_active_display.short_description = 'Status'


@admin.register(EPGEntry)
class EPGEntryAdmin(admin.ModelAdmin):
    """
    Admin interface for managing EPG (Electronic Program Guide) entries.
    
    Provides comprehensive scheduling management with time-based
    filtering and conflict detection capabilities.
    """
    list_display = [
        'channel', 
        'show', 
        'start_time', 
        'end_time',
        'duration_display', 
        'episode_info',
        'status_indicators',
        'created_at'
    ]
    list_filter = [
        'channel', 
        'start_time', 
        'is_premiere',
        'is_finale', 
        'is_repeat', 
        'is_live',
        'created_at'
    ]
    search_fields = [
        'show__title', 
        'episode_title', 
        'episode_description',
        'channel__name'
    ]
    readonly_fields = [
        'id', 
        'created_at', 
        'updated_at'
    ]
    date_hierarchy = 'start_time'
    fieldsets = (
        ('Schedule Information', {
            'fields': ('channel', 'show', 'start_time', 'end_time')
        }),
        ('Episode Details', {
            'fields': (
                'episode_title', 'episode_number', 'season_number',
                'episode_description'
            )
        }),
        ('Broadcast Properties', {
            'fields': (
                'is_premiere', 'is_finale', 'is_repeat', 'is_live'
            )
        }),
        ('Language & Accessibility', {
            'fields': ('audio_language', 'subtitle_language')
        }),
        ('Metadata', {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def duration_display(self, obj):
        """
        Display the duration of the EPG entry.
        """
        duration = obj.duration
        hours = duration.total_seconds() // 3600
        minutes = (duration.total_seconds() % 3600) // 60
        return f"{int(hours):02d}:{int(minutes):02d}"
    duration_display.short_description = 'Duration'
    
    def episode_info(self, obj):
        """
        Display episode information in a compact format.
        """
        info_parts = []
        if obj.season_number:
            info_parts.append(f"S{obj.season_number}")
        if obj.episode_number:
            info_parts.append(f"E{obj.episode_number}")
        if obj.episode_title:
            info_parts.append(obj.episode_title[:30] + ('...' if len(obj.episode_title) > 30 else ''))
        return ' - '.join(info_parts) if info_parts else 'No episode info'
    episode_info.short_description = 'Episode Info'
    
    def status_indicators(self, obj):
        """
        Display status indicators for special broadcast properties.
        """
        indicators = []
        if obj.is_live:
            indicators.append('<span style="color: red;">🔴 LIVE</span>')
        if obj.is_premiere:
            indicators.append('<span style="color: gold;">⭐ PREMIERE</span>')
        if obj.is_finale:
            indicators.append('<span style="color: purple;">🏁 FINALE</span>')
        if obj.is_repeat:
            indicators.append('<span style="color: gray;">🔄 REPEAT</span>')
        if obj.is_currently_airing:
            indicators.append('<span style="color: green;">📺 ON AIR</span>')
        
        return format_html(' '.join(indicators)) if indicators else 'Standard'
    status_indicators.short_description = 'Status'
    
    def get_queryset(self, request):
        """
        Optimize queryset with select_related for better performance.
        """
        return super().get_queryset(request).select_related('channel', 'show')


# Custom admin site configuration
admin.site.site_header = "Ad-tlas TV Channels Administration"
admin.site.site_title = "TV Channels Admin"
admin.site.index_title = "Welcome to TV Channels Management"