from django.contrib import admin
from django.utils.html import format_html
from .models import Brand, Category, Product, ProductImage


@admin.register(Brand)
class BrandAdmin(admin.ModelAdmin):
    list_display = ('name', 'logo_preview', 'is_active', 'product_count', 'created_at')
    list_filter = ('is_active', 'created_at')
    search_fields = ('name',)
    prepopulated_fields = {'slug': ('name',)}
    list_editable = ('is_active',)

    def logo_preview(self, obj):
        if obj.logo:
            return format_html(
                '<img src="{}" width="40" height="40" style="object-fit: contain; border-radius: 4px;" />',
                obj.logo.url
            )
        return '-'
    logo_preview.short_description = 'Logo'

    def product_count(self, obj):
        return obj.products.count()
    product_count.short_description = 'Products'


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'parent', 'order', 'image_preview', 'is_active', 'product_count', 'created_at')
    list_filter = ('is_active', 'parent', 'created_at')
    search_fields = ('name',)
    prepopulated_fields = {'slug': ('name',)}
    list_editable = ('is_active', 'order')
    autocomplete_fields = ('parent',)

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

    def product_count(self, obj):
        return obj.products.count()
    product_count.short_description = 'Products'


class ProductImageInline(admin.TabularInline):
    model = ProductImage
    extra = 1
    fields = ('image', 'alt_text', 'is_primary', 'order', 'image_preview')
    readonly_fields = ('image_preview',)

    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" width="60" height="60" style="object-fit: cover; border-radius: 4px;" />',
                obj.image.url
            )
        return '-'
    image_preview.short_description = 'Preview'


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = (
        'image_preview', 'name', 'sku', 'category', 'brand', 
        'price_display', 'stock_status', 'status', 'is_featured', 'created_at'
    )
    list_display_links = ('image_preview', 'name')
    list_filter = ('status', 'is_featured', 'category', 'brand', 'created_at')
    search_fields = ('name', 'sku', 'part_number', 'description')
    prepopulated_fields = {'slug': ('name',)}
    autocomplete_fields = ('category', 'brand')
    list_editable = ('status', 'is_featured')
    date_hierarchy = 'created_at'
    ordering = ('-created_at',)
    inlines = [ProductImageInline]

    list_display = (
    'image_preview', 'name', 'sku', 'category', 'brand', 
    'price_display', 'stock_status', 'status', 'is_featured', 'is_top_rated', 'created_at'
    )

    list_filter = ('status', 'is_featured', 'is_top_rated', 'category', 'brand', 'created_at')

    list_editable = ('status', 'is_featured', 'is_top_rated')
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'slug', 'sku', 'part_number')
        }),
        ('Description', {
            'fields': ('short_description', 'description')
        }),
        ('Categorization', {
            'fields': ('category', 'brand')
        }),
        ('Pricing', {
            'fields': ('price', 'sale_price')
        }),
        ('Inventory', {
            'fields': ('stock_quantity', 'low_stock_threshold')
        }),
        ('Media', {
            'fields': ('main_image',)
        }),
        ('Vehicle Compatibility', {
            'fields': ('compatible_vehicles',),
            'classes': ('collapse',)
        }),
        ('Status & Visibility', {
            'fields': ('status', 'is_featured')
        }),
        ('SEO', {
            'fields': ('meta_title', 'meta_description'),
            'classes': ('collapse',)
        }),
    )

    def image_preview(self, obj):
        if obj.main_image:
            return format_html(
                '<img src="{}" width="50" height="50" style="object-fit: cover; border-radius: 4px;" />',
                obj.main_image.url
            )
        return format_html(
            '<div style="width: 50px; height: 50px; background: #e5e7eb; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #9ca3af; font-size: 10px;">No Image</div>'
        )
    image_preview.short_description = 'Image'

    def price_display(self, obj):
        if obj.is_on_sale:
            return format_html(
                '<span style="text-decoration: line-through; color: #9ca3af;">AED {}</span> '
                '<span style="color: #dc2626; font-weight: bold;">AED {}</span>',
                obj.price, obj.sale_price
            )
        return format_html('AED {}', obj.price)
    price_display.short_description = 'Price'

    def stock_status(self, obj):
        if obj.stock_quantity == 0:
            return format_html(
                '<span style="color: #dc2626; font-weight: bold;">Out of Stock</span>'
            )
        elif obj.is_low_stock:
            return format_html(
                '<span style="color: #f59e0b; font-weight: bold;">{} (Low)</span>',
                obj.stock_quantity
            )
        return format_html(
            '<span style="color: #10b981;">{}</span>',
            obj.stock_quantity
        )
    stock_status.short_description = 'Stock'

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


@admin.register(ProductImage)
class ProductImageAdmin(admin.ModelAdmin):
    list_display = ('product', 'image_preview', 'is_primary', 'order', 'created_at')
    list_filter = ('is_primary', 'created_at')
    search_fields = ('product__name', 'alt_text')
    list_editable = ('is_primary', 'order')
    autocomplete_fields = ('product',)

    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" width="60" height="60" style="object-fit: cover; border-radius: 4px;" />',
                obj.image.url
            )
        return '-'
    image_preview.short_description = 'Preview'
    