from django.contrib import admin
from django.utils.html import format_html
from .models import Service, ServiceFeature, ServiceExpertise, ServiceCategory


class ServiceFeatureInline(admin.TabularInline):
    model = ServiceFeature
    extra = 0
    fields = ['title', 'description', 'icon', 'display_order']
    ordering = ['display_order']


class ServiceExpertiseInline(admin.TabularInline):
    model = ServiceExpertise
    extra = 0
    fields = ['title', 'description', 'icon', 'display_order']
    ordering = ['display_order']


@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'category', 'price', 'duration', 'deliverables_preview', 'featured', 'display_order', 'is_active', 'created_at']
    list_filter = ['featured', 'is_active', 'category', 'created_at']
    search_fields = ['title', 'description', 'slug', 'short_description', 'technologies', 'deliverables']
    prepopulated_fields = {'slug': ('title',)}
    ordering = ['display_order', 'title']
    inlines = [ServiceFeatureInline, ServiceExpertiseInline]
    actions = ['mark_as_featured', 'mark_as_not_featured']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('title', 'slug', 'description', 'short_description', 'icon', 'image', 'image_url')
        }),
        ('Category & Classification', {
            'fields': ('category', 'featured', 'display_order', 'is_active')
        }),
        ('Project Details', {
            'fields': ('duration', 'deliverables', 'technologies', 'process_steps'),
            'description': 'Define what the client will receive and the project timeline'
        }),
        ('Section Descriptions', {
            'fields': ('features_description', 'deliverables_description', 'process_description', 'why_choose_description', 'expertise_description'),
            'description': 'Customize descriptions for each section on the service detail page',
            'classes': ('collapse',)
        }),
        ('Pricing', {
            'fields': ('price',)
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # Make deliverables field more prominent
        if 'deliverables' in form.base_fields:
            form.base_fields['deliverables'].widget.attrs.update({
                'rows': 4,
                'cols': 80,
                'placeholder': 'Enter what the client will receive (e.g., Complete web application, Admin dashboard, Documentation, Testing, Deployment)'
            })
        return form
    
    def deliverables_preview(self, obj):
        """Display a preview of deliverables in the list view"""
        if obj.deliverables:
            # Show first 50 characters of deliverables
            preview = obj.deliverables[:50]
            if len(obj.deliverables) > 50:
                preview += "..."
            return format_html('<span title="{}">{}</span>', obj.deliverables, preview)
        return format_html('<span style="color: #999;">No deliverables defined</span>')
    deliverables_preview.short_description = 'Deliverables Preview'
    
    def mark_as_featured(self, request, queryset):
        """Admin action to mark services as featured"""
        updated = queryset.update(featured=True)
        self.message_user(request, f'{updated} service(s) marked as featured.')
    mark_as_featured.short_description = "Mark selected services as featured"
    
    def mark_as_not_featured(self, request, queryset):
        """Admin action to mark services as not featured"""
        updated = queryset.update(featured=False)
        self.message_user(request, f'{updated} service(s) marked as not featured.')
    mark_as_not_featured.short_description = "Mark selected services as not featured"


@admin.register(ServiceFeature)
class ServiceFeatureAdmin(admin.ModelAdmin):
    list_display = ['title', 'service', 'display_order']
    list_filter = ['service', 'display_order']
    search_fields = ['title', 'description', 'service__title']
    ordering = ['service', 'display_order']


@admin.register(ServiceExpertise)
class ServiceExpertiseAdmin(admin.ModelAdmin):
    list_display = ['title', 'service', 'display_order']
    list_filter = ['service', 'display_order']
    search_fields = ['title', 'description', 'service__title']
    ordering = ['service', 'display_order']


@admin.register(ServiceCategory)
class ServiceCategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'slug', 'display_order', 'is_active']
    list_filter = ['is_active', 'display_order']
    search_fields = ['name', 'description', 'slug']
    prepopulated_fields = {'slug': ('name',)}
    ordering = ['display_order', 'name']