"""Advertisers Admin Configuration

This module configures the Django admin interface for the advertisers app.
Provides comprehensive admin views for managing agencies, brands, and relationships.

Admin Classes:
    - AgencyAdmin: Admin interface for agencies
    - BrandAdmin: Admin interface for brands
    - BrandCategoryAdmin: Admin interface for brand categories
    - UserAdvertiserAdmin: Admin interface for user-advertiser relationships
"""

from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.db.models import Count, Sum
from django.utils import timezone

from .models import Agency, Brand, BrandCategory, UserAdvertiser


@admin.register(BrandCategory)
class BrandCategoryAdmin(admin.ModelAdmin):
    """Admin interface for BrandCategory model.
    
    Provides hierarchical category management with tree view.
    """
    
    list_display = [
        'name', 'parent', 'brands_count', 'subcategories_count', 'created_at'
    ]
    list_filter = ['parent', 'created_at']
    search_fields = ['name', 'description']
    ordering = ['name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'description')
        }),
        ('Hierarchy', {
            'fields': ('parent',)
        }),
    )
    
    def brands_count(self, obj):
        """Display number of brands in this category."""
        count = obj.brands.filter(status='active').count()
        if count > 0:
            url = reverse('admin:advertisers_brand_changelist')
            return format_html(
                '<a href="{}?category__id__exact={}">{} brands</a>',
                url, obj.id, count
            )
        return '0 brands'
    brands_count.short_description = 'Brands'
    
    def subcategories_count(self, obj):
        """Display number of subcategories."""
        count = obj.subcategories.count()
        return f"{count} subcategories"
    subcategories_count.short_description = 'Subcategories'


class BrandInline(admin.TabularInline):
    """Inline admin for brands within agency admin."""
    
    model = Brand
    extra = 0
    fields = ['name', 'category', 'status', 'annual_budget']
    readonly_fields = ['created_at', 'updated_at']
    
    def get_queryset(self, request):
        """Optimize queryset for inline display."""
        return super().get_queryset(request).select_related('category')


@admin.register(Agency)
class AgencyAdmin(admin.ModelAdmin):
    """Admin interface for Agency model.
    
    Provides comprehensive agency management with statistics and relationships.
    """
    
    list_display = [
        'name', 'contact_person', 'email', 'city', 'country',
        'brands_count', 'campaigns_count', 'status', 'created_at'
    ]
    list_filter = [
        'status', 'country', 'city', 'created_at', 'updated_at'
    ]
    search_fields = [
        'name', 'description', 'email', 'contact_person', 'city', 'country'
    ]
    ordering = ['name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'description', 'status')
        }),
        ('Contact Information', {
            'fields': ('email', 'phone', 'contact_person')
        }),
        ('Location', {
            'fields': ('address', 'city', 'country')
        }),
        ('Online Presence', {
            'fields': ('website', 'logo')
        }),
        ('Management', {
            'fields': ('owner',)
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    inlines = [BrandInline]
    
    def get_queryset(self, request):
        """Optimize queryset with related data."""
        return super().get_queryset(request).select_related('owner').prefetch_related('brands')
    
    def brands_count(self, obj):
        """Display number of brands for this agency."""
        count = obj.brands.filter(status='active').count()
        if count > 0:
            url = reverse('admin:advertisers_brand_changelist')
            return format_html(
                '<a href="{}?agency__id__exact={}">{} brands</a>',
                url, obj.id, count
            )
        return '0 brands'
    brands_count.short_description = 'Brands'
    
    def campaigns_count(self, obj):
        """Display number of campaigns for this agency."""
        count = obj.total_campaigns
        return f"{count} campaigns"
    campaigns_count.short_description = 'Campaigns'
    
    def save_model(self, request, obj, form, change):
        """Set owner when creating new agency."""
        if not change and not obj.owner:
            obj.owner = request.user
        super().save_model(request, obj, form, change)


class UserAdvertiserInline(admin.TabularInline):
    """Inline admin for user-advertiser relationships within brand admin."""
    
    model = UserAdvertiser
    extra = 0
    fields = ['user', 'role', 'is_active']
    readonly_fields = ['created_at', 'updated_at']
    
    def get_queryset(self, request):
        """Optimize queryset for inline display."""
        return super().get_queryset(request).select_related('user')


@admin.register(Brand)
class BrandAdmin(admin.ModelAdmin):
    """Admin interface for Brand model.
    
    Provides comprehensive brand management with statistics and relationships.
    """
    
    list_display = [
        'name', 'agency', 'category', 'industry', 'annual_budget',
        'campaigns_count', 'status', 'created_at'
    ]
    list_filter = [
        'status', 'agency', 'category', 'industry', 'created_at', 'updated_at'
    ]
    search_fields = [
        'name', 'description', 'industry', 'target_audience',
        'agency__name', 'category__name'
    ]
    ordering = ['name']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'description', 'status')
        }),
        ('Classification', {
            'fields': ('agency', 'category', 'industry')
        }),
        ('Contact Information', {
            'fields': ('contact_email', 'contact_phone')
        }),
        ('Online Presence', {
            'fields': ('website', 'logo')
        }),
        ('Business Information', {
            'fields': ('target_audience', 'annual_budget')
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    inlines = [UserAdvertiserInline]
    
    def get_queryset(self, request):
        """Optimize queryset with related data."""
        return super().get_queryset(request).select_related(
            'agency', 'category'
        ).prefetch_related('campaigns')
    
    def campaigns_count(self, obj):
        """Display number of campaigns for this brand."""
        count = obj.total_campaigns
        if count > 0:
            # Assuming campaigns app exists
            try:
                url = reverse('admin:campaigns_campaign_changelist')
                return format_html(
                    '<a href="{}?advertiser__id__exact={}">{} campaigns</a>',
                    url, obj.id, count
                )
            except:
                return f"{count} campaigns"
        return '0 campaigns'
    campaigns_count.short_description = 'Campaigns'
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """Customize foreign key fields."""
        if db_field.name == "agency":
            # Filter agencies based on user permissions
            if not request.user.is_superuser:
                kwargs["queryset"] = Agency.objects.filter(
                    owner=request.user
                )
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(UserAdvertiser)
class UserAdvertiserAdmin(admin.ModelAdmin):
    """Admin interface for UserAdvertiser relationship model.
    
    Manages user-brand relationships with roles and permissions.
    """
    
    list_display = [
        'user', 'brand', 'agency_name', 'role', 'is_active', 'created_at'
    ]
    list_filter = [
        'role', 'is_active', 'brand__agency', 'created_at', 'updated_at'
    ]
    search_fields = [
        'user__username', 'user__email', 'user__first_name', 'user__last_name',
        'brand__name', 'brand__agency__name'
    ]
    ordering = ['-created_at']
    
    fieldsets = (
        ('Relationship', {
            'fields': ('user', 'brand')
        }),
        ('Access Control', {
            'fields': ('role', 'permissions', 'is_active')
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    
    def get_queryset(self, request):
        """Optimize queryset with related data."""
        return super().get_queryset(request).select_related(
            'user', 'brand', 'brand__agency'
        )
    
    def agency_name(self, obj):
        """Display agency name for the brand."""
        return obj.brand.agency.name
    agency_name.short_description = 'Agency'
    agency_name.admin_order_field = 'brand__agency__name'
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """Customize foreign key fields based on user permissions."""
        if db_field.name == "brand":
            # Filter brands based on user permissions
            if not request.user.is_superuser:
                kwargs["queryset"] = Brand.objects.filter(
                    agency__owner=request.user
                )
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


# ============================================================================
# Custom Admin Actions
# ============================================================================

@admin.action(description='Activate selected agencies')
def activate_agencies(modeladmin, request, queryset):
    """Bulk activate agencies."""
    updated = queryset.update(status='active')
    modeladmin.message_user(
        request,
        f"{updated} agencies were successfully activated."
    )


@admin.action(description='Deactivate selected agencies')
def deactivate_agencies(modeladmin, request, queryset):
    """Bulk deactivate agencies."""
    updated = queryset.update(status='inactive')
    modeladmin.message_user(
        request,
        f"{updated} agencies were successfully deactivated."
    )


@admin.action(description='Activate selected brands')
def activate_brands(modeladmin, request, queryset):
    """Bulk activate brands."""
    updated = queryset.update(status='active')
    modeladmin.message_user(
        request,
        f"{updated} brands were successfully activated."
    )


@admin.action(description='Deactivate selected brands')
def deactivate_brands(modeladmin, request, queryset):
    """Bulk deactivate brands."""
    updated = queryset.update(status='inactive')
    modeladmin.message_user(
        request,
        f"{updated} brands were successfully deactivated."
    )


# Add actions to admin classes
AgencyAdmin.actions = [activate_agencies, deactivate_agencies]
BrandAdmin.actions = [activate_brands, deactivate_brands]


# ============================================================================
# Admin Site Customization
# ============================================================================

# Customize admin site header and title
admin.site.site_header = "Adtlas Advertisers Administration"
admin.site.site_title = "Adtlas Advertisers Admin"
admin.site.index_title = "Welcome to Adtlas Advertisers Administration"