from django.contrib import admin
from django.utils.html import format_html
from blog.models import PCategory, Post, PComment, PCategoryView


class ChildInline(admin.TabularInline):
    """Alt kategorileri inline olarak göster"""
    model = PCategory
    extra = 0
    fk_name = 'parent'
    fields = ('title', 'is_active', 'order', 'slug')
    readonly_fields = ('slug',)


@admin.register(PCategory)
class PCategoryAdmin(admin.ModelAdmin):
    list_display = ('title', 'parent', 'is_active', 'order', 'created_at', 'post_count', 'view_count', 'image_preview')
    list_filter = ('is_active', 'created_at', 'parent')
    search_fields = ('title', 'keywords', 'description', 'slug')
    list_editable = ('order', 'is_active')
    prepopulated_fields = {'slug': ('title',)}
    readonly_fields = ('created_at', 'updated_at', 'image_preview', 'view_count')

    fieldsets = (
        ('Temel Bilgiler', {
            'fields': ('title', 'parent', 'order', 'is_active')
        }),
        ('SEO Bilgileri', {
            'fields': ('slug', 'keywords', 'description')
        }),
        ('Görsel', {
            'fields': ('image', 'image_preview')
        }),
        ('Tarihler', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    inlines = [ChildInline]

    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" width="100" height="100" style="object-fit: cover;" />', obj.image.url)
        return "Resim Yok"
    image_preview.short_description = 'Resim Önizleme'

    def post_count(self, obj):
        return obj.post_categories.count()
    post_count.short_description = 'Post Sayısı'

    def view_count(self, obj):
        return obj.category_views.count()
    view_count.short_description = 'Görüntülenme'

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.prefetch_related('post_categories', 'category_views')
        return queryset


class PostCategoriesInline(admin.TabularInline):
    """Post kategorilerini inline olarak göster"""
    model = Post.categories.through
    extra = 1
    verbose_name = 'Kategori'
    verbose_name_plural = 'Kategoriler'


@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'user', 'is_active', 'is_front', 'created_at', 'comment_count', 'image_preview')
    list_filter = ('is_active', 'is_front', 'created_at', 'updated_at', 'categories')
    search_fields = ('title', 'content', 'keywords', 'slug')
    list_editable = ('is_active', 'is_front')
    readonly_fields = ('created_at', 'updated_at', 'slug', 'image_preview', 'thumb_preview', 'thumb', 'parent')
    filter_horizontal = ('categories',)

    fieldsets = (
        ('Temel Bilgiler', {
            'fields': ('title', 'user', 'content', 'categories')
        }),
        ('SEO ve Medya', {
            'fields': ('slug', 'keywords', 'video')
        }),
        ('Görseller', {
            'fields': ('image', 'image_preview', 'thumb_preview'),
            'description': 'Thumb otomatik oluşturulur, image yüklediğinizde.'
        }),
        ('Durum', {
            'fields': ('is_active', 'is_front', 'parent')
        }),
        ('Tarihler', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{0}" width="150" height="90" style="object-fit: cover; border: 1px solid #ddd;" />', obj.image.url)
        return "Resim Yok"
    image_preview.short_description = 'Ana Resim Önizleme'

    def thumb_preview(self, obj):
        if obj.thumb:
            return format_html('<img src="{0}" width="100" height="60" style="object-fit: cover; border: 1px solid #ddd;" />', obj.thumb.url)
        return "Thumb Yok (Kaydet ve otomatik oluşur)"
    thumb_preview.short_description = 'Thumb Önizleme'

    def comment_count(self, obj):
        return obj._post.filter(is_active=True).count()
    comment_count.short_description = 'Yorum Sayısı'

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.prefetch_related('categories', '_post').select_related('user')
        return queryset

    def save_model(self, request, obj, form, change):
        """Post kaydedilirken user otomatik atanabilir"""
        if not obj.user:
            obj.user = request.user
        super().save_model(request, obj, form, change)


class ChildCommentInline(admin.TabularInline):
    """Alt yorumları inline olarak göster"""
    model = PComment
    extra = 0
    fk_name = 'parent'
    fields = ('user', 'title', 'body', 'is_active')
    readonly_fields = ('user',)


@admin.register(PComment)
class PCommentAdmin(admin.ModelAdmin):
    list_display = ('title', 'user', 'post', 'parent', 'is_active', 'created_at', 'child_count')
    list_filter = ('is_active', 'created_at', 'post')
    search_fields = ('title', 'body', 'user__username', 'user__email', 'post__title')
    list_editable = ('is_active',)
    readonly_fields = ('created_at', 'updated_at', 'slug', 'user', 'post')

    fieldsets = (
        ('Yorum Bilgileri', {
            'fields': ('user', 'post', 'parent')
        }),
        ('İçerik', {
            'fields': ('title', 'body', 'slug')
        }),
        ('Durum', {
            'fields': ('is_active',)
        }),
        ('Tarihler', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    inlines = [ChildCommentInline]

    def child_count(self, obj):
        return obj.child.count()
    child_count.short_description = 'Alt Yorum Sayısı'

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.select_related('user', 'post', 'parent').prefetch_related('child')
        return queryset


@admin.register(PCategoryView)
class PCategoryViewAdmin(admin.ModelAdmin):
    list_display = ('category', 'ip_address', 'created_at', 'short_user_agent')
    list_filter = ('created_at', 'category')
    search_fields = ('ip_address', 'user_agent', 'category__title')
    readonly_fields = ('category', 'ip_address', 'user_agent', 'created_at')
    date_hierarchy = 'created_at'

    def short_user_agent(self, obj):
        if obj.user_agent:
            return obj.user_agent[:50] + '...' if len(obj.user_agent) > 50 else obj.user_agent
        return '-'
    short_user_agent.short_description = 'User Agent'

    def has_add_permission(self, request):
        """Kategori ziyaretleri manuel eklenemez"""
        return False

    def has_change_permission(self, request, obj=None):
        """Kategori ziyaretleri düzenlenemez"""
        return False

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.select_related('category')
        return queryset
