from django.contrib import admin
from django.utils.html import format_html
from .models import Category, News, ImageGallery


class ImageGalleryInline(admin.TabularInline):
    """Inline admin for ImageGallery"""
    model = ImageGallery
    extra = 1
    fields = ['image', 'caption', 'order']


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """Admin interface for Category model"""
    list_display = ['name', 'slug', 'image_preview', 'created_at', 'news_count']
    search_fields = ['name', 'description']
    prepopulated_fields = {'slug': ('name',)}
    readonly_fields = ['created_at', 'updated_at', 'image_preview']
    
    def news_count(self, obj):
        """Display count of news items in this category"""
        return obj.news_items.count()
    news_count.short_description = 'News Count'

    def image_preview(self, obj):
        """Show a small preview of the featured image"""
        if obj.featured_image:
            return format_html('<img src="{}" style="height:40px; width:auto; object-fit:contain;"/>', obj.featured_image.url)
        return "-"
    image_preview.short_description = 'Featured Image'


@admin.register(News)
class NewsAdmin(admin.ModelAdmin):
    """Admin interface for News model"""
    list_display = ['title', 'category', 'publish_date', 'is_active', 'created_at']
    list_filter = ['is_active', 'category', 'publish_date', 'created_at']
    search_fields = ['title', 'short_description', 'description']
    prepopulated_fields = {'slug': ('title',)}
    readonly_fields = ['created_at', 'updated_at']
    date_hierarchy = 'publish_date'
    ordering = ['-publish_date', '-created_at']
    inlines = [ImageGalleryInline]
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('title', 'slug', 'category', 'is_active')
        }),
        ('SEO & Content', {
            'fields': ('short_description', 'description', 'featured_image')
        }),
        ('Publishing', {
            'fields': ('publish_date',)
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )


@admin.register(ImageGallery)
class ImageGalleryAdmin(admin.ModelAdmin):
    """Admin interface for ImageGallery model"""
    list_display = ['news', 'caption', 'order', 'uploaded_at']
    list_filter = ['uploaded_at']
    search_fields = ['news__title', 'caption']
    readonly_fields = ['uploaded_at']
    ordering = ['news', 'order', 'uploaded_at']
