from django.contrib import admin

from . import models


@admin.register(models.ProductCategory)
class ProductCategoryAdmin(admin.ModelAdmin):
    list_display = ("name", "slug", "display_order", "is_active")
    list_filter = ("is_active",)
    search_fields = ("name", "slug")
    ordering = ("display_order", "name")
    prepopulated_fields = {"slug": ("name",)}


@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = (
        "name",
        "category",
        "price",
        "inventory_quantity",
        "max_per_order",
        "is_active",
        "is_featured",
    )
    list_filter = ("category", "is_active", "is_featured")
    search_fields = ("name", "slug")
    prepopulated_fields = {"slug": ("name",)}
    autocomplete_fields = ("category",)


@admin.register(models.DeliveryZone)
class DeliveryZoneAdmin(admin.ModelAdmin):
    list_display = ("label", "postal_code", "is_active")
    list_filter = ("is_active",)
    search_fields = ("label", "postal_code")


@admin.register(models.DeliveryOverrideCode)
class DeliveryOverrideCodeAdmin(admin.ModelAdmin):
    list_display = ("code", "label", "max_uses", "usage_count", "is_active")
    list_filter = ("is_active",)
    search_fields = ("code", "label")


class OrderItemInline(admin.TabularInline):
    model = models.OrderItem
    extra = 0
    readonly_fields = (
        "product",
        "product_name",
        "product_slug",
        "unit_price",
        "quantity",
        "line_subtotal",
    )


@admin.register(models.Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = (
        "id",
        "customer_name",
        "fulfillment_method",
        "status",
        "scheduled_date",
        "total_amount",
        "created_at",
    )
    list_filter = (
        "fulfillment_method",
        "status",
        "scheduled_date",
        "delivery_postal_code",
    )
    search_fields = ("id", "customer_name", "customer_email")
    date_hierarchy = "scheduled_date"
    inlines = [OrderItemInline]
    readonly_fields = (
        "subtotal_amount",
        "tax_amount",
        "delivery_fee_amount",
        "discount_amount",
        "total_amount",
        "created_at",
        "updated_at",
    )
