from django.contrib import admin
from .models import Category, Book, Order
from django.utils.html import format_html

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'book_count', 'display_image')
    prepopulated_fields = {'slug': ('name',)}
    
    def book_count(self, obj):
        return obj.books.count()
    book_count.short_description = 'Books'

    def display_image(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="width: 40px; height: 40px; border-radius: 50%;" />', obj.image.url)
        return "-"
    display_image.short_description = 'Image'

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'category', 'price', 'is_featured', 'display_cover', 'created_at')
    list_filter = ('category', 'is_featured', 'created_at')
    list_editable = ('is_featured',)
    search_fields = ('title', 'description')
    prepopulated_fields = {'slug': ('title',)}
    
    def display_cover(self, obj):
        if obj.cover_image:
            return format_html('<img src="{}" style="width: 50px; height: 70px; border-radius: 4px;" />', obj.cover_image.url)
        return "-"
    display_cover.short_description = 'Cover'

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('book', 'user_email', 'transaction_id', 'status', 'display_screenshot', 'created_at')
    list_filter = ('status', 'created_at')
    search_fields = ('user_email', 'transaction_id')
    actions = ['approve_orders', 'reject_orders']

    def approve_orders(self, request, queryset):
        queryset.update(status='approved')
    approve_orders.short_description = "✅ Mark as Approved"

    def reject_orders(self, request, queryset):
        queryset.update(status='rejected')
    reject_orders.short_description = "❌ Mark as Rejected"

    def display_screenshot(self, obj):
        if obj.payment_screenshot:
            return format_html('<a href="{}" target="_blank"><img src="{}" style="width: 50px; height: 50px; border-radius: 4px;" /></a>', obj.payment_screenshot.url, obj.payment_screenshot.url)
        return "No Proof"
    display_screenshot.short_description = 'Payment Proof'