"""
Admin classes for services and service offerings
"""

from django.contrib import admin
from django.utils.html import format_html

from ..models import Service, ServiceOffering, ExternalLink, ExternalLinkOffering, Plan


class ExternalLinkInline(admin.TabularInline):
    """Inline admin for ExternalLink model"""

    model = ExternalLink
    extra = 1
    fields = ("description", "url", "order")
    ordering = ("order", "description")


class ExternalLinkOfferingInline(admin.TabularInline):
    """Inline admin for ExternalLinkOffering model"""

    model = ExternalLinkOffering
    extra = 1
    fields = ("description", "url", "order")
    ordering = ("order", "description")


class PlanInline(admin.StackedInline):
    """Inline admin for Plan model"""

    model = Plan
    extra = 1
    fieldsets = (
        (None, {"fields": ("name", "description", "pricing", "plan_description")}),
    )


class OfferingInline(admin.StackedInline):
    """Inline admin for ServiceOffering model"""

    model = ServiceOffering
    extra = 1
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "description",
                    "service",
                    "cloud_provider",
                    "offer_description",
                )
            },
        ),
    )
    show_change_link = True


@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
    """Admin configuration for Service model"""

    list_display = (
        "name",
        "logo_preview",
        "category_list",
        "is_featured",
        "is_coming_soon",
        "disable_listing",
    )
    list_filter = ("categories",)
    search_fields = ("name", "description", "slug")
    prepopulated_fields = {"slug": ("name",)}
    filter_horizontal = ("categories",)
    inlines = [ExternalLinkInline, OfferingInline]

    def logo_preview(self, obj):
        """Display logo preview in admin list view"""
        if obj.logo:
            return format_html(
                '<img src="{}" style="max-height: 50px;"/>', obj.logo.url
            )
        return "No logo"

    logo_preview.short_description = "Logo"

    def category_list(self, obj):
        """Display categories as comma-separated list"""
        return ", ".join([cat.name for cat in obj.categories.all()])

    category_list.short_description = "Categories"

    def partner_list(self, obj):
        """Display consulting partners as comma-separated list"""
        return ", ".join([partner.name for partner in obj.consulting_partners.all()])

    partner_list.short_description = "Consulting Partners"


@admin.register(ServiceOffering)
class ServiceOfferingAdmin(admin.ModelAdmin):
    """Admin configuration for ServiceOffering model"""

    list_display = ("service", "cloud_provider")
    list_filter = ("service", "cloud_provider")
    search_fields = ("service__name", "cloud_provider__name", "description")
    inlines = [ExternalLinkOfferingInline, PlanInline]
