from django.contrib import admin
from django.utils.html import format_html

from .models import Dress


@admin.register(Dress)
class DressAdmin(admin.ModelAdmin):
    list_display = ("thumbnail_preview", "name", "category", "price", "is_active", "created_at")
    list_display_links = ("thumbnail_preview", "name")
    list_filter = ("category", "is_active")
    search_fields = ("name",)
    list_editable = ("is_active",)
    readonly_fields = ("thumbnail_preview", "image_preview", "created_at")
    fields = ("name", "category", "garment_type", "price", "raw_image", "remove_model", "sleeves", "is_active",
              "image_preview", "created_at")
    actions = ["reprocess_images"]

    @admin.action(description="Re-run background / model removal on selected dresses")
    def reprocess_images(self, request, queryset):
        for dress in queryset:
            dress._process_images()
        self.message_user(request, f"Reprocessed {queryset.count()} dress(es).")

    @admin.display(description="Thumbnail")
    def thumbnail_preview(self, obj):
        if obj.thumbnail:
            return format_html('<img src="{}" style="height:60px;border-radius:4px;background:#eee">', obj.thumbnail.url)
        return "—"

    @admin.display(description="Transparent result")
    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="max-height:300px;background:#ddd">', obj.image.url)
        return "Generated after saving."
