"""
Social admin
"""
from django.contrib import admin
from django.utils.html import format_html

from .models import SocialMention


@admin.register(SocialMention)
class SocialMentionAdmin(admin.ModelAdmin):
    """Social mention admin"""
    list_display = [
        'platform', 'author_username', 'content_preview',
        'sentiment_badge', 'hospital', 'action_created',
        'responded', 'posted_at'
    ]
    list_filter = [
        'platform', 'sentiment', 'action_created', 'responded',
        'hospital', 'posted_at'
    ]
    search_fields = [
        'content', 'content_ar', 'author_username', 'author_name', 'post_id'
    ]
    ordering = ['-posted_at']
    date_hierarchy = 'posted_at'
    
    fieldsets = (
        ('Platform & Source', {
            'fields': ('platform', 'post_url', 'post_id')
        }),
        ('Author', {
            'fields': ('author_username', 'author_name', 'author_followers')
        }),
        ('Content', {
            'fields': ('content', 'content_ar')
        }),
        ('Organization', {
            'fields': ('hospital', 'department')
        }),
        ('Sentiment Analysis', {
            'fields': ('sentiment', 'sentiment_score', 'sentiment_analyzed_at')
        }),
        ('Engagement', {
            'fields': ('likes_count', 'shares_count', 'comments_count')
        }),
        ('Response', {
            'fields': ('responded', 'response_text', 'responded_at', 'responded_by')
        }),
        ('Action', {
            'fields': ('action_created', 'px_action')
        }),
        ('Timestamps', {
            'fields': ('posted_at', 'collected_at', 'created_at', 'updated_at')
        }),
        ('Metadata', {
            'fields': ('metadata',),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = [
        'sentiment_analyzed_at', 'responded_at', 'posted_at',
        'collected_at', 'created_at', 'updated_at'
    ]
    
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('hospital', 'department', 'responded_by', 'px_action')
    
    def content_preview(self, obj):
        """Show preview of content"""
        return obj.content[:100] + '...' if len(obj.content) > 100 else obj.content
    content_preview.short_description = 'Content'
    
    def sentiment_badge(self, obj):
        """Display sentiment with badge"""
        if not obj.sentiment:
            return '-'
        
        colors = {
            'positive': 'success',
            'neutral': 'secondary',
            'negative': 'danger',
        }
        color = colors.get(obj.sentiment, 'secondary')
        
        return format_html(
            '<span class="badge bg-{}">{}</span>',
            color,
            obj.get_sentiment_display()
        )
    sentiment_badge.short_description = 'Sentiment'
