from django.contrib import admin
from .models import Status, StatusView


@admin.register(Status)
class StatusAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'user',
        'media_type',
        'created_at',
        'expires_at',
        'is_expired_display',
        'time_remaining_display',
        'views_count'
    ]
    list_filter = ['media_type', 'created_at', 'expires_at']
    search_fields = ['user__username', 'content']
    readonly_fields = ['created_at', 'expires_at']
    date_hierarchy = 'created_at'
    
    def is_expired_display(self, obj):
        return '✅ Yes' if obj.is_expired() else '❌ No'
    is_expired_display.short_description = 'Expired?'
    
    def time_remaining_display(self, obj):
        remaining = obj.time_remaining()
        if remaining == 0:
            return 'Expired'
        minutes = remaining // 60
        seconds = remaining % 60
        return f'{minutes}m {seconds}s'
    time_remaining_display.short_description = 'Time Remaining'
    
    def views_count(self, obj):
        return obj.views.count()
    views_count.short_description = 'Views'
    
    actions = ['delete_expired_status']
    
    def delete_expired_status(self, request, queryset):
        from django.utils import timezone
        expired = queryset.filter(expires_at__lte=timezone.now())
        count = expired.count()
        expired.delete()
        self.message_user(
            request,
            f'{count} expired status deleted successfully.'
        )
    delete_expired_status.short_description = 'Delete expired status'


@admin.register(StatusView)
class StatusViewAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'status',
        'viewer',
        'viewed_at',
        'status_owner'
    ]
    list_filter = ['viewed_at']
    search_fields = ['viewer__username', 'status__user__username']
    readonly_fields = ['viewed_at']
    date_hierarchy = 'viewed_at'
    
    def status_owner(self, obj):
        return obj.status.user.username
    status_owner.short_description = 'Status Owner'