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

from .models import Article, ArticleTranslation, Category, CategoryTranslation


# ─── Admin Site Configuration ───────────────────────────────────────────────
admin.site.site_header = "APECB — Administration"
admin.site.site_title = "APECB Admin"
admin.site.index_title = "Tableau de bord"


# ─── Category ───────────────────────────────────────────────────────────────
class CategoryTranslationInline(admin.TabularInline):
    model = CategoryTranslation
    extra = 0
    min_num = 2
    max_num = 2
    fields = ('language', 'name')

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        # Pre-fill the languages for new categories
        if not obj:
            formset.initial = [
                {'language': 'fr'},
                {'language': 'ar'},
            ]
        return formset


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('slug', 'get_name_fr', 'get_name_ar', 'article_count', 'created_at')
    search_fields = ('slug', 'translations__name')
    readonly_fields = ('created_at',)
    prepopulated_fields = {'slug': ()}
    inlines = [CategoryTranslationInline]

    @admin.display(description="Nom (FR)")
    def get_name_fr(self, obj):
        return obj.get_name('fr')

    @admin.display(description="الاسم (AR)")
    def get_name_ar(self, obj):
        return obj.get_name('ar')

    @admin.display(description="Nb articles")
    def article_count(self, obj):
        count = obj.articles.count()
        return format_html('<b>{}</b>', count)


# ─── Article ────────────────────────────────────────────────────────────────
class ArticleTranslationInline(admin.StackedInline):
    model = ArticleTranslation
    extra = 0
    min_num = 2
    max_num = 2
    fields = (
        'language',
        'title',
        'excerpt',
        'content',
        ('meta_title', 'meta_description'),
        'keywords',
    )
    classes = ('collapse',)

    def get_formset(self, request, obj=None, **kwargs):
        formset = super().get_formset(request, obj, **kwargs)
        if not obj:
            formset.initial = [
                {'language': 'fr'},
                {'language': 'ar'},
            ]
        return formset


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):

    # ── List view ──────────────────────────────────────────────────
    list_display = (
        'get_thumbnail_preview',
        'get_title_fr',
        'category',
        'author',
        'status',
        'is_pinned',
        'is_adherent',
        'published_date',
        'created_at',
    )
    list_display_links = ('get_title_fr',)
    list_filter = ('status', 'category', 'is_pinned', 'is_adherent', 'author', 'created_at')
    list_editable = ('status', 'is_pinned', 'is_adherent')
    list_per_page = 20
    search_fields = ('slug', 'translations__title', 'translations__excerpt')
    date_hierarchy = 'created_at'
    ordering = ('-created_at',)

    # ── Detail view ────────────────────────────────────────────────
    fieldsets = (
        ("Informations principales", {
            'fields': ('slug', 'category', 'author', 'thumbnail', 'get_thumbnail_display')
        }),
        ("Publication", {
            'fields': ('status', 'is_pinned', 'is_adherent', 'published_date')
        }),
        ("Dates", {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',),
        }),
    )
    readonly_fields = ('created_at', 'updated_at', 'get_thumbnail_display')
    prepopulated_fields = {'slug': ()}
    autocomplete_fields = ('category',)
    raw_id_fields = ('author',)
    inlines = [ArticleTranslationInline]

    # ── Actions ────────────────────────────────────────────────────
    actions = ['publish_articles', 'unpublish_articles', 'pin_articles', 'unpin_articles']

    @admin.action(description="✅ Publier les articles sélectionnés")
    def publish_articles(self, request, queryset):
        updated = queryset.update(status='published', published_date=timezone.now())
        self.message_user(request, f"{updated} article(s) publié(s).")

    @admin.action(description="📝 Repasser en brouillon")
    def unpublish_articles(self, request, queryset):
        updated = queryset.update(status='draft')
        self.message_user(request, f"{updated} article(s) repassé(s) en brouillon.")

    @admin.action(description="📌 Épingler les articles sélectionnés")
    def pin_articles(self, request, queryset):
        updated = queryset.update(is_pinned=True)
        self.message_user(request, f"{updated} article(s) épinglé(s).")

    @admin.action(description="📌 Désépingler les articles sélectionnés")
    def unpin_articles(self, request, queryset):
        updated = queryset.update(is_pinned=False)
        self.message_user(request, f"{updated} article(s) désépinglé(s).")

    # ── Custom columns ─────────────────────────────────────────────
    @admin.display(description="Titre (FR)")
    def get_title_fr(self, obj):
        return obj.get_title('fr')



    @admin.display(description="Vignette")
    def get_thumbnail_preview(self, obj):
        if obj.thumbnail:
            return format_html(
                '<img src="{}" style="width: 60px; height: 40px; '
                'object-fit: cover; border-radius: 4px;" />',
                obj.thumbnail.url
            )
        return format_html(
            '<span style="color: #999; font-style: italic;">—</span>'
        )

    @admin.display(description="Aperçu vignette")
    def get_thumbnail_display(self, obj):
        if obj.thumbnail:
            return format_html(
                '<img src="{}" style="max-width: 300px; max-height: 200px; '
                'border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);" />',
                obj.thumbnail.url
            )
        return format_html(
            '<span style="color: #999;">Aucune vignette</span>'
        )

    def save_formset(self, request, form, formset, change):
        """After saving translations, regenerate slug if needed."""
        instances = formset.save()
        if instances and not change:
            # New article — regenerate slug from FR translation
            article = form.instance
            if article.slug.startswith('article-'):
                article.regenerate_slug()

    def save_model(self, request, obj, form, change):
        """Auto-assign author on creation."""
        if not change and not obj.author:
            obj.author = request.user
        super().save_model(request, obj, form, change)
