from django.contrib import admin
from django.utils.html import format_html
from .models import Category, Tag, News, NewsGallery, Comment, Advertisement, SiteSettings


class NewsGalleryInline(admin.TabularInline):
    """Inline admin for news gallery images"""
    model = NewsGallery
    extra = 1
    fields = ['image', 'caption', 'order']


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """Admin interface for Category model"""
    list_display = ['name', 'slug', 'is_active', 'order', 'created_at', 'image_preview']
    list_filter = ['is_active', 'created_at']
    search_fields = ['name', 'description']
    prepopulated_fields = {'slug': ('name',)}
    list_editable = ['is_active', 'order']
    ordering = ['order', 'name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'slug', 'description', 'image')
        }),
        ('Settings', {
            'fields': ('is_active', 'order')
        }),
    )
    
    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" width="50" height="50" style="object-fit: cover; border-radius: 5px;" />', obj.image.url)
        return '-'
    image_preview.short_description = 'Image'


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    """Admin interface for Tag model"""
    list_display = ['name', 'slug', 'news_count']
    search_fields = ['name']
    prepopulated_fields = {'slug': ('name',)}
    
    def news_count(self, obj):
        return obj.news_articles.count()
    news_count.short_description = 'Articles'


@admin.register(News)
class NewsAdmin(admin.ModelAdmin):
    """Admin interface for News model"""
    list_display = ['title', 'category', 'author', 'status', 'is_featured', 'is_breaking', 
                    'views_count', 'published_at', 'image_preview']
    list_filter = ['status', 'is_featured', 'is_breaking', 'category', 'published_at', 'created_at']
    search_fields = ['title', 'summary', 'content']
    prepopulated_fields = {'slug': ('title',)}
    list_editable = ['status', 'is_featured', 'is_breaking']
    date_hierarchy = 'published_at'
    filter_horizontal = ['tags']
    inlines = [NewsGalleryInline]
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('title', 'slug', 'category', 'tags', 'author')
        }),
        ('Content', {
            'fields': ('summary', 'content')
        }),
        ('Images', {
            'fields': ('featured_image', 'thumbnail')
        }),
        ('Publishing', {
            'fields': ('status', 'is_featured', 'is_breaking', 'published_at')
        }),
        ('SEO', {
            'fields': ('meta_description', 'meta_keywords'),
            'classes': ('collapse',)
        }),
        ('Statistics', {
            'fields': ('views_count',),
            'classes': ('collapse',)
        }),
    )
    
    def image_preview(self, obj):
        if obj.featured_image:
            return format_html('<img src="{}" width="60" height="40" style="object-fit: cover; border-radius: 5px;" />', obj.featured_image.url)
        return '-'
    image_preview.short_description = 'Image'
    
    def save_model(self, request, obj, form, change):
        if not obj.pk:
            obj.author = request.user
        super().save_model(request, obj, form, change)
    
    class Media:
        css = {
            'all': ('admin/css/custom_admin.css',)
        }


@admin.register(NewsGallery)
class NewsGalleryAdmin(admin.ModelAdmin):
    """Admin interface for NewsGallery model"""
    list_display = ['news', 'caption', 'order', 'created_at', 'image_preview']
    list_filter = ['created_at']
    search_fields = ['news__title', 'caption']
    list_editable = ['order']
    
    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" width="60" height="40" style="object-fit: cover; border-radius: 5px;" />', obj.image.url)
        return '-'
    image_preview.short_description = 'Image'


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    """Admin interface for Comment model"""
    list_display = ['name', 'news', 'is_approved', 'created_at', 'content_preview']
    list_filter = ['is_approved', 'created_at']
    search_fields = ['name', 'email', 'content', 'news__title']
    list_editable = ['is_approved']
    date_hierarchy = 'created_at'
    
    fieldsets = (
        ('Comment Information', {
            'fields': ('news', 'name', 'email', 'content')
        }),
        ('Moderation', {
            'fields': ('is_approved',)
        }),
    )
    
    def content_preview(self, obj):
        return obj.content[:50] + '...' if len(obj.content) > 50 else obj.content
    content_preview.short_description = 'Content'
    
    actions = ['approve_comments', 'unapprove_comments']
    
    def approve_comments(self, request, queryset):
        updated = queryset.update(is_approved=True)
        self.message_user(request, f'{updated} comment(s) approved.')
    approve_comments.short_description = 'Approve selected comments'
    
    def unapprove_comments(self, request, queryset):
        updated = queryset.update(is_approved=False)
        self.message_user(request, f'{updated} comment(s) unapproved.')
    unapprove_comments.short_description = 'Unapprove selected comments'


@admin.register(Advertisement)
class AdvertisementAdmin(admin.ModelAdmin):
    """Admin interface for Advertisement model"""
    list_display = ['title', 'position', 'is_active', 'start_date', 'end_date', 
                    'order', 'image_preview']
    list_filter = ['position', 'is_active', 'start_date', 'end_date']
    search_fields = ['title']
    list_editable = ['is_active', 'order']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('title', 'image', 'link')
        }),
        ('Placement', {
            'fields': ('position', 'order')
        }),
        ('Schedule', {
            'fields': ('is_active', 'start_date', 'end_date')
        }),
    )
    
    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" width="100" height="60" style="object-fit: cover; border-radius: 5px;" />', obj.image.url)
        return '-'
    image_preview.short_description = 'Image'


@admin.register(SiteSettings)
class SiteSettingsAdmin(admin.ModelAdmin):
    """Admin interface for Site Settings"""
    fieldsets = (
        ('Site Information', {
            'fields': ('site_name', 'site_logo', 'site_favicon', 'site_description')
        }),
        ('Contact Information', {
            'fields': ('contact_email', 'contact_phone', 'address')
        }),
        ('Social Media', {
            'fields': ('facebook_url', 'twitter_url', 'instagram_url', 'youtube_url')
        }),
        ('Footer', {
            'fields': ('footer_text', 'copyright_text')
        }),
    )
    
    def has_add_permission(self, request):
        # Only allow one instance
        return not SiteSettings.objects.exists()
    
    def has_delete_permission(self, request, obj=None):
        # Prevent deletion of site settings
        return False


# Customize admin site header and grouping
admin.site.site_header = '📰 News Portal Administration'
admin.site.site_title = 'News Portal Admin'
admin.site.index_title = 'Welcome to News Portal Admin Dashboard'

# Reorder admin app labels for better organization
admin.site.index_title = 'Site Administration'
