from django.contrib import admin
from django.utils.html import format_html
from posts.models import Post, PostImage, PostVideo


class PostImageInline(admin.TabularInline):
    model = PostImage
    extra = 0
    raw_id_fields = ['image']
    readonly_fields = ['image_preview']

    def image_preview(self, obj):
        if obj.image and obj.image.image:
            return format_html('<img src="{}" width="50" height="50" />', obj.image.image.url)
        return '-'
    image_preview.short_description = 'Preview'


class PostVideoInline(admin.TabularInline):
    model = PostVideo
    extra = 0
    raw_id_fields = ['video']


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'content_preview', 'created_by_display', 'category',
        'audience_badge', 'group_badge', 'media_count', 'interaction_stats',
        'created_at', 'status_badge'
    ]
    list_filter = ['audience', 'is_active', 'is_updated', 'category', 'created_at']
    search_fields = ['content', 'created_by__username', 'category__title']
    raw_id_fields = ['created_by', 'category', 'group']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    readonly_fields = ['created_at', 'updated_at', 'shared_count']
    list_select_related = ['created_by', 'category', 'group']
    inlines = [PostImageInline, PostVideoInline]

    fieldsets = (
        ('Content', {
            'fields': ('content', 'category', 'group')
        }),
        ('Author & Visibility', {
            'fields': ('created_by', 'audience')
        }),
        ('Interaction Settings', {
            'fields': ('allow_likes', 'allow_comments', 'allow_sharing', 'allow_saving'),
            'classes': ('collapse',)
        }),
        ('Display Settings', {
            'fields': ('show_comments', 'show_likes_count', 'show_shares_count'),
            'classes': ('collapse',)
        }),
        ('Status', {
            'fields': ('is_active', 'is_updated', 'shared_count', 'created_at', 'updated_at')
        }),
    )

    def content_preview(self, obj):
        preview = obj.content[:40] + '...' if len(obj.content) > 40 else obj.content
        return preview or '(No content)'
    content_preview.short_description = 'Content'

    def created_by_display(self, obj):
        return obj.created_by.username
    created_by_display.short_description = 'Author'
    created_by_display.admin_order_field = 'created_by__username'

    def audience_badge(self, obj):
        colors = {
            'PUBLIC': '#28a745',
            'FOLLOWERS': '#007bff',
            'CLOSE_FRIENDS': '#fd7e14',
            'ONLY_ME': '#6c757d',
        }
        icons = {
            'PUBLIC': '🌍',
            'FOLLOWERS': '👥',
            'CLOSE_FRIENDS': '⭐',
            'ONLY_ME': '🔒',
        }
        color = colors.get(obj.audience, '#6c757d')
        icon = icons.get(obj.audience, '')
        return format_html(
            '<span style="background-color: {}; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px;">{} {}</span>',
            color, icon, obj.audience
        )
    audience_badge.short_description = 'Audience'

    def group_badge(self, obj):
        if obj.group:
            return format_html(
                '<span style="background-color: #17a2b8; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px;">👥 {}</span>',
                obj.group.name[:15]
            )
        return '-'
    group_badge.short_description = 'Group'

    def media_count(self, obj):
        images = obj.images.count()
        videos = obj.videos.count()
        parts = []
        if images:
            parts.append(f'📷 {images}')
        if videos:
            parts.append(f'🎬 {videos}')
        return ' '.join(parts) if parts else '-'
    media_count.short_description = 'Media'

    def interaction_stats(self, obj):
        likes = obj.likepost_set.count()
        comments = obj.comments.count()
        return format_html('❤️ {} 💬 {}', likes, comments)
    interaction_stats.short_description = 'Interactions'

    def status_badge(self, obj):
        if not obj.is_active:
            return format_html('<span style="color: red;">🗑️ Deleted</span>')
        if obj.is_updated:
            return format_html('<span style="color: orange;">✏️ Edited</span>')
        return format_html('<span style="color: green;">✅ Active</span>')
    status_badge.short_description = 'Status'


@admin.register(PostImage)
class PostImageAdmin(admin.ModelAdmin):
    list_display = ['id', 'post_preview', 'image_preview', 'order']
    list_filter = ['order']
    raw_id_fields = ['post', 'image']
    ordering = ['post', 'order']

    def post_preview(self, obj):
        return f"Post #{obj.post_id}"
    post_preview.short_description = 'Post'

    def image_preview(self, obj):
        if obj.image and obj.image.image:
            return format_html('<img src="{}" width="50" height="50" />', obj.image.image.url)
        return '-'
    image_preview.short_description = 'Image'


@admin.register(PostVideo)
class PostVideoAdmin(admin.ModelAdmin):
    list_display = ['id', 'post_preview', 'video_file', 'order']
    list_filter = ['order']
    raw_id_fields = ['post', 'video']
    ordering = ['post', 'order']

    def post_preview(self, obj):
        return f"Post #{obj.post_id}"
    post_preview.short_description = 'Post'

    def video_file(self, obj):
        if obj.video and obj.video.file:
            return format_html('🎬 {}', obj.video.file.name.split('/')[-1])
        return '-'
    video_file.short_description = 'Video'