from django.contrib import admin
from .models import Category, Product, StockMovement

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'parent', 'is_active', 'created_at')
    list_filter = ('is_active', 'parent', 'created_at')
    search_fields = ('name', 'description')
    ordering = ('name',)
    
    fieldsets = (
        (None, {'fields': ('name', 'description', 'parent')}),
        ('Status', {'fields': ('is_active',)}),
    )

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'code', 'category', 'current_stock', 'cost_price', 
                   'selling_price', 'unit', 'is_active', 'is_manufactured')
    list_filter = ('category', 'unit', 'is_active', 'is_manufactured', 'created_at')
    search_fields = ('name', 'code', 'description')
    ordering = ('name',)
    
    fieldsets = (
        ('Basic Information', {'fields': ('name', 'code', 'description', 'category', 'unit')}),
        ('Stock Information', {'fields': ('current_stock', 'min_stock_level', 'max_stock_level')}),
        ('Pricing', {'fields': ('cost_price', 'selling_price')}),
        ('Product Details', {'fields': ('weight', 'dimensions')}),
        ('Status', {'fields': ('is_active', 'is_manufactured')}),
    )
    
    readonly_fields = ('current_stock',)
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('category')

@admin.register(StockMovement)
class StockMovementAdmin(admin.ModelAdmin):
    list_display = ('product', 'movement_type', 'quantity', 'unit_price', 
                   'total_value', 'date', 'created_by')
    list_filter = ('movement_type', 'date', 'created_by', 'product__category')
    search_fields = ('product__name', 'product__code', 'notes', 'reference_note')
    ordering = ('-date', '-created_at')
    
    fieldsets = (
        ('Movement Details', {'fields': ('product', 'movement_type', 'quantity', 'unit_price')}),
        ('Reference Information', {'fields': ('reference_type', 'reference_id', 'reference_note')}),
        ('Additional Information', {'fields': ('date', 'notes', 'created_by')}),
    )
    
    readonly_fields = ('total_value',)
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('product', 'created_by')
