from django.contrib import admin
from .models import ManufacturingOrder, ManufacturingLine, ManufacturingOrderLine

@admin.register(ManufacturingOrder)
class ManufacturingOrderAdmin(admin.ModelAdmin):
    list_display = ('order_number', 'product', 'quantity', 'date', 'status', 
                   'total_cost', 'created_by', 'created_at')
    list_filter = ('status', 'date', 'product__category', 'created_by', 'created_at')
    search_fields = ('order_number', 'product__name', 'product__code', 'notes')
    ordering = ('-date', '-created_at')
    
    fieldsets = (
        ('Order Information', {'fields': ('order_number', 'date', 'product', 'quantity', 'status')}),
        ('Cost Information', {'fields': ('labor_cost', 'overhead_cost', 'total_cost')}),
        ('Additional Information', {'fields': ('notes', 'created_by')}),
    )
    
    readonly_fields = ('total_cost',)
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('product', 'created_by')

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

@admin.register(ManufacturingOrderLine)
class ManufacturingOrderLineAdmin(admin.ModelAdmin):
    list_display = ('manufacturing_order', 'manufacturing_line', 'actual_quantity', 
                   'start_time', 'end_time')
    list_filter = ('manufacturing_line', 'start_time', 'end_time')
    search_fields = ('manufacturing_order__order_number', 'notes')
    ordering = ('-start_time',)
    
    fieldsets = (
        ('Line Information', {'fields': ('manufacturing_order', 'manufacturing_line')}),
        ('Timing', {'fields': ('start_time', 'end_time')}),
        ('Production', {'fields': ('actual_quantity', 'notes')}),
    )
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('manufacturing_order', 'manufacturing_line')
