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

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug')
    prepopulated_fields = {'slug': ('name',)}

@admin.register(Vendor)
class VendorAdmin(admin.ModelAdmin):
    list_display = ('name', 'whatsapp_number', 'created_at')
    prepopulated_fields = {'slug': ('name',)}
    search_fields = ('name', 'whatsapp_number')

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'vendor', 'category', 'price', 'stock', 'is_active', 'created_at')
    list_filter = ('vendor', 'category', 'is_active')
    prepopulated_fields = {'slug': ('name',)}
    search_fields = ('name', 'vendor__name', 'category__name')

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        # Filter products by the vendor linked to the user
        try:
            vendor = request.user.vendor_profile
            return qs.filter(vendor=vendor)
        except:
            return qs.none()

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if not request.user.is_superuser:
            # If a vendor is logged in, hide the 'vendor' field from the form
            if 'vendor' in form.base_fields:
                form.base_fields['vendor'].required = False
                # Remove it from the displayed fields if it's there
                # However, for simplicity, we'll just handle it in save_model
        return form

    def save_model(self, request, obj, form, change):
        if not request.user.is_superuser:
            # Automatically set the vendor if it's not set and the user is a vendor
            try:
                obj.vendor = request.user.vendor_profile
            except:
                pass
        super().save_model(request, obj, form, change)

    def get_fieldsets(self, request, obj=None):
        fieldsets = super().get_fieldsets(request, obj)
        if not request.user.is_superuser:
            # Exclude vendor field from the form for vendors
            for fieldset in fieldsets:
                if 'vendor' in fieldset[1]['fields']:
                    # Create a new tuple without 'vendor'
                    new_fields = tuple(f for f in fieldset[1]['fields'] if f != 'vendor')
                    fieldset[1]['fields'] = new_fields
        return fieldsets
