from django.contrib import admin
from .models import (
    SiteSettings, StaticPage, ContactMessage,
    AboutPageContent, ContactPageContent, SubmitPageContent,
    TeamPageContent, EditorialBoardMember, Contributor,
    YouTubeVideo,
    HomepageContent, HomepageSection, SubscribeContent, FooterContent, NavContent,
    VisitorLog, PopupModal
)

admin.site.site_header  = "The Reverse Times — Editorial"
admin.site.site_title   = "Reverse Times Admin"
admin.site.index_title  = "Editorial Dashboard"


# ─── Site Settings ─────────────────────────────────────────────────────────────

@admin.register(SiteSettings)
class SiteSettingsAdmin(admin.ModelAdmin):
    fieldsets = (
        ('🌐 General', {
            'fields': ('site_name', 'tagline', 'logo', 'favicon', 'contact_email'),
        }),
        ('📝 Content', {
            'fields': ('about_text', 'footer_text'),
        }),
        ('🔗 Social Links', {
            'description': 'Add your social media profile URLs. Leave blank to hide from the footer.',
            'fields': ('social_facebook', 'social_twitter', 'social_instagram',
                       'social_youtube', 'social_linkedin', 'social_tiktok',
                       'social_threads', 'social_reddit', 'social_whatsapp'),
        }),
        ('🔤 Fonts', {
            'description': 'Change any font independently. English and Bangla text each use their own font; '
                           'Bangla digits use “Bangla labels, buttons & numbers”.',
            'fields': (('font_en_heading', 'font_bn_heading'), ('font_en_body', 'font_bn_body'),
                       ('font_en_label', 'font_bn_ui'), 'font_en_accent'),
        }),
        ('🏠 Homepage', {
            'fields': ('homepage_hero_count', 'homepage_featured_count', 'hero_layout', 'hero_autoplay_seconds'),
            'description': 'When “Homepage hero slides” has active slides, the hero becomes a slider '
                           '(same look as the Overlay layout). With no slides, the layout below is used.',
            'classes': ('collapse',),
        }),
        ('🔍 SEO, Search Console & Analytics', {
            'description': 'Verify the site in Google Search Console and Bing Webmaster Tools, then submit '
                           'https://thereversetimes.com/sitemap.xml in both.',
            'fields': ('meta_description', 'google_site_verification', 'bing_site_verification',
                       'google_analytics_id', 'meta_keywords'),
        }),
        ('⚙️ System', {
            'fields': ('maintenance_mode',),
            'classes': ('collapse',),
        }),
    )
    def has_add_permission(self, request):
        return not SiteSettings.objects.exists()
    def has_delete_permission(self, request, obj=None):
        return False


# ─── Static Pages ──────────────────────────────────────────────────────────────

@admin.register(StaticPage)
class StaticPageAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'is_published', 'show_in_footer', 'updated_at']
    prepopulated_fields = {'slug': ('title',)}
    list_filter = ['is_published', 'show_in_footer']
    search_fields = ['title', 'content']


# ─── Contact Messages ─────────────────────────────────────────────────────────

@admin.register(ContactMessage)
class ContactMessageAdmin(admin.ModelAdmin):
    list_display = ['name', 'email', 'purpose', 'status', 'has_attachment', 'created_at']
    list_filter = ['status', 'purpose', 'created_at']
    search_fields = ['name', 'email', 'message']
    list_editable = ['status']
    readonly_fields = ['name', 'email', 'purpose', 'message', 'attachment', 'created_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']

    fieldsets = (
        ('Sender Info', {
            'fields': ('name', 'email', 'purpose', 'created_at'),
        }),
        ('Message', {
            'fields': ('message', 'attachment'),
        }),
        ('Admin', {
            'fields': ('status', 'admin_notes'),
        }),
    )

    def has_attachment(self, obj):
        return bool(obj.attachment)
    has_attachment.boolean = True
    has_attachment.short_description = "📎"

    def has_add_permission(self, request):
        return False  # Messages come from the public form only


# ─── Singleton Admin Base ──────────────────────────────────────────────────────

class SingletonAdmin(admin.ModelAdmin):
    """Base admin for singleton (one-row) page content models."""
    def has_add_permission(self, request):
        return not self.model.objects.exists()
    def has_delete_permission(self, request, obj=None):
        return False
    def changelist_view(self, request, extra_context=None):
        obj = self.model.get_solo()
        from django.shortcuts import redirect
        from django.urls import reverse
        app_label = self.model._meta.app_label
        model_name = self.model._meta.model_name
        return redirect(reverse(f'admin:{app_label}_{model_name}_change', args=[obj.pk]))


# ─── About Page ────────────────────────────────────────────────────────────────

@admin.register(AboutPageContent)
class AboutPageAdmin(SingletonAdmin):
    fieldsets = (
        ('🏠 Hero Section', {
            'fields': ('hero_badge', 'hero_title', 'hero_tagline'),
        }),
        ('📖 Our Story', {
            'fields': ('our_story',),
            'description': 'Rich-text content for the "Our Story" section.',
        }),
        ('🎯 Mission', {
            'fields': ('mission_quote', 'mission_body'),
        }),
        ('🔗 Call to Action', {
            'fields': ('cta_title', 'cta_subtitle'),
            'classes': ('collapse',),
        }),
    )


# ─── Contact Page ──────────────────────────────────────────────────────────────

@admin.register(ContactPageContent)
class ContactPageAdmin(SingletonAdmin):
    fieldsets = (
        ('🏠 Hero Section', {
            'fields': ('hero_badge', 'hero_title', 'hero_tagline'),
        }),
        ('ℹ️ Info Panel', {
            'fields': ('info_title', 'info_description'),
        }),
        ('📧 Contact Details', {
            'fields': ('email_address', 'response_time'),
        }),
    )


# ─── Submit Page ───────────────────────────────────────────────────────────────

@admin.register(SubmitPageContent)
class SubmitPageAdmin(SingletonAdmin):
    fieldsets = (
        ('🏠 Hero Section', {
            'fields': ('hero_badge', 'hero_title', 'hero_tagline'),
        }),
        ('📝 Guidelines Panel', {
            'fields': ('guidelines_title', 'guidelines_description'),
        }),
    )


# ─── Team Page ─────────────────────────────────────────────────────────────────

@admin.register(TeamPageContent)
class TeamPageAdmin(SingletonAdmin):
    fieldsets = (
        ('🏠 Hero Section', {
            'fields': ('hero_badge', 'hero_title', 'hero_tagline'),
        }),
        ('👥 Editorial Board Section', {
            'fields': ('board_label', 'board_title', 'board_description'),
        }),
        ('✍️ Contributors Section', {
            'fields': ('contrib_label', 'contrib_title', 'contrib_description'),
        }),
        ('🔗 Join CTA', {
            'fields': ('cta_title', 'cta_description'),
            'classes': ('collapse',),
        }),
    )



# ─── Standalone Team Member Admin (also accessible directly) ──────────────────

@admin.register(EditorialBoardMember)
class EditorialBoardMemberAdmin(admin.ModelAdmin):
    list_display = ['name', 'role', 'order', 'is_active']
    list_editable = ['order', 'is_active']
    list_filter = ['is_active']
    search_fields = ['name', 'role']
    ordering = ['order', 'name']

@admin.register(Contributor)
class ContributorAdmin(admin.ModelAdmin):
    list_display = ['name', 'role', 'specialty', 'order', 'is_active']
    list_editable = ['order', 'is_active']
    list_filter = ['is_active']
    search_fields = ['name', 'role', 'specialty']
    ordering = ['order', 'name']


# ─── YouTube Videos ───────────────────────────────────────────────────────────

@admin.register(YouTubeVideo)
class YouTubeVideoAdmin(admin.ModelAdmin):
    list_display = ['title', 'embed_url', 'order', 'is_active', 'created_at']
    list_editable = ['order', 'is_active']
    list_filter = ['is_active']
    search_fields = ['title', 'description']
    ordering = ['order', '-created_at']


# ─── Homepage Content ─────────────────────────────────────────────────────────

@admin.register(HomepageContent)
class HomepageContentAdmin(SingletonAdmin):
    fieldsets = (
        ('📰 Navigation Bar', {
            'fields': ('volume_label',),
        }),
        ('🏠 Hero Section', {
            'fields': ('hero_cta_text',),
        }),
        ('📋 Section Headings', {
            'fields': ('featured_label', 'editorial_label', 'archives_label', 'recent_label', 'youtube_label', 'timeline_label'),
            'description': 'These headings appear above each section on the homepage.',
        }),
    )


@admin.register(HomepageSection)
class HomepageSectionAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'category', 'max_articles', 'show_view_all', 'order', 'is_active']
    list_editable = ['max_articles', 'show_view_all', 'order', 'is_active']
    list_filter = ['is_active']
    ordering = ['order']


# ─── Subscribe Section ────────────────────────────────────────────────────────

@admin.register(SubscribeContent)
class SubscribeContentAdmin(SingletonAdmin):
    fieldsets = (
        ('📧 Subscribe Section', {
            'fields': ('heading', 'description', 'button_text'),
        }),
        ('📝 Form Placeholders', {
            'fields': ('name_placeholder', 'email_placeholder'),
            'classes': ('collapse',),
        }),
    )


# ─── Footer Content ───────────────────────────────────────────────────────────

@admin.register(FooterContent)
class FooterContentAdmin(SingletonAdmin):
    fieldsets = (
        ('🏷️ Brand', {
            'fields': ('brand_name', 'brand_description'),
        }),
        ('📋 Column Headings', {
            'fields': ('sections_heading', 'about_heading', 'archives_heading'),
        }),
        ('⚖️ Legal & Copyright', {
            'fields': ('copyright_text', 'privacy_url', 'terms_url', 'cookie_url'),
        }),
    )


# ─── Navigation Content ───────────────────────────────────────────────────────

@admin.register(NavContent)
class NavContentAdmin(SingletonAdmin):
    fieldsets = (
        ('🔍 Search', {
            'fields': ('search_placeholder',),
        }),
        ('📂 "More" Dropdown', {
            'fields': ('more_label', 'archives_text', 'subscribe_text', 'editorial_text', 'about_text', 'submit_text', 'contact_text'),
        }),
    )


# ─── Analytics ────────────────────────────────────────────────────────────────

class RealVisitorFilter(admin.SimpleListFilter):
    title = 'visitor type'
    parameter_name = 'real'

    def lookups(self, request, model_admin):
        return (('yes', 'Real visitors (default)'), ('old', 'Old unfiltered logs (may include bots)'), ('all', 'Everything'))

    def choices(self, changelist):
        value = self.value() or 'yes'
        for lookup, title in self.lookup_choices:
            yield {'selected': value == lookup, 'query_string': changelist.get_query_string({self.parameter_name: lookup}),
                   'display': title}

    def queryset(self, request, queryset):
        value = self.value() or 'yes'
        if value == 'yes':
            return queryset.filter(is_human=True)
        if value == 'old':
            return queryset.filter(is_human=False)
        return queryset


@admin.register(VisitorLog)
class VisitorLogAdmin(admin.ModelAdmin):
    change_list_template = 'admin/core/visitorlog/change_list.html'
    list_display = ['page_visited', 'time_spent', 'visitor_short', 'user', 'device', 'referrer_host', 'visit_time']
    list_filter = [RealVisitorFilter, 'device', 'visit_time']
    search_fields = ['page_visited', 'visitor_id', 'referrer', 'user__email']
    date_hierarchy = 'visit_time'
    list_per_page = 100
    readonly_fields = [f.name for f in VisitorLog._meta.fields]

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    @admin.display(description='Time on page', ordering='time_spent_seconds')
    def time_spent(self, obj):
        m, s = divmod(obj.time_spent_seconds, 60)
        return f"{m}m {s:02d}s" if m else f"{s}s"

    @admin.display(description='Visitor', ordering='visitor_id')
    def visitor_short(self, obj):
        return (obj.visitor_id or '')[:8] or '—'

    @admin.display(description='Came from')
    def referrer_host(self, obj):
        from urllib.parse import urlparse
        return urlparse(obj.referrer).netloc if obj.referrer else 'direct / internal'

    def changelist_view(self, request, extra_context=None):
        from datetime import timedelta
        from django.db.models import Avg, Count, Sum
        from django.utils import timezone
        now = timezone.now()
        real = VisitorLog.objects.filter(is_human=True)
        stats = []
        for label, since in (('Today', now.replace(hour=0, minute=0, second=0, microsecond=0)),
                             ('Last 7 days', now - timedelta(days=7)), ('Last 30 days', now - timedelta(days=30))):
            qs = real.filter(visit_time__gte=since)
            agg = qs.aggregate(views=Count('id'), people=Count('visitor_id', distinct=True),
                               total=Sum('time_spent_seconds'), avg=Avg('time_spent_seconds'))
            stats.append({'label': label, 'people': agg['people'], 'views': agg['views'],
                          'minutes': round((agg['total'] or 0) / 60), 'avg': round(agg['avg'] or 0)})
        top = (real.filter(visit_time__gte=now - timedelta(days=7)).values('page_visited')
               .annotate(n=Count('id'), t=Sum('time_spent_seconds')).order_by('-n')[:8])
        extra_context = {**(extra_context or {}), 'visit_stats': stats, 'top_pages': top}
        return super().changelist_view(request, extra_context)


@admin.register(PopupModal)
class PopupModalAdmin(admin.ModelAdmin):
    list_display = ['title', 'delay_seconds', 'is_active', 'created_at']
    list_filter = ['is_active', 'created_at']
    search_fields = ['title', 'subtitle', 'button_text']
    list_editable = ['is_active', 'delay_seconds']


# ─── Homepage blocks ───────────────────────────────────────────────────────────

from .models import HomepageBlock  # noqa: E402


@admin.register(HomepageBlock)
class HomepageBlockAdmin(admin.ModelAdmin):
    list_display = ('title', 'kind', 'showing', 'max_items', 'see_all_text', 'theme', 'order', 'is_active')

    @admin.display(description='Showing now')
    def showing(self, obj):
        from django.utils.html import format_html
        if obj.kind == 'text':
            return 'Text'
        n = len(obj.items())
        if n:
            return f'{n} item(s)'
        return format_html('<span style="color:#b34a2e">0 — shows “coming soon” until you add items</span>')
    list_editable = ('order', 'is_active')
    list_filter = ('kind', 'is_active')
    filter_horizontal = ('products', 'articles')
    fieldsets = (
        (None, {'fields': ('kind', 'eyebrow', 'title', 'subtitle', 'theme', 'order', 'is_active'),
                'description': 'Sections appear on the homepage after the featured stories, in “Order”. '
                               'Magazine / Wearable History / Nostalgic sections fill themselves with the latest items.'}),
        ('Cards', {'fields': ('max_items', 'products', 'articles', 'category'),
                   'description': 'Pick products for “Hand-picked products”, articles for “Hand-picked articles”, '
                                  'or a category for “Latest articles from a category”.'}),
        ('Custom text', {'fields': ('body', 'image'), 'classes': ('collapse',)}),
        ('“See all” button', {'fields': ('see_all_text', 'see_all_url'),
                              'description': 'Leave the link blank to use the matching page automatically.'}),
    )

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == 'articles':
            from apps.articles.models import Article
            kwargs['queryset'] = Article.objects.filter(status='published').order_by('-published_at')
        return super().formfield_for_manytomany(db_field, request, **kwargs)


# ─── Homepage hero slider ──────────────────────────────────────────────────────

from .models import HeroSlide  # noqa: E402


@admin.register(HeroSlide)
class HeroSlideAdmin(admin.ModelAdmin):
    list_display = ('preview', 'slide_title', 'kind', 'order', 'is_active', 'schedule')
    list_display_links = ('preview', 'slide_title')
    list_editable = ('order', 'is_active')
    list_filter = ('kind', 'is_active')
    autocomplete_fields = ('article',)
    fieldsets = (
        ('What this slide shows', {
            'fields': ('kind', 'article', 'product'),
            'description': 'Pick a blog article, a magazine issue or a shop product — the slide fills in its title, text, '
                           'picture and buttons automatically. Or choose “Custom” and write your own. '
                           'Magazine slides get “buy digital” and “order print” buttons; product slides get “add to cart”. '
                           'Seconds per slide: Admin → Site settings.'}),
        ('Change the text (optional)', {'fields': ('eyebrow', 'title', 'text', 'button_text', 'button_url')}),
        ('Picture (optional)', {'fields': ('image', 'image_position')}),
        ('On phones', {'fields': ('phone_display', 'phone_image'),
                       'description': 'For magazine and shop slides: show the cover/product photo on phones, or your own '
                                      'phone background picture. With “background picture” chosen and no picture uploaded, '
                                      'the slide shows no picture on phones — just the text and buttons.'}),
        ('Order & schedule', {'fields': ('order', 'is_active', 'starts_at', 'ends_at')}),
    )

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'product':
            from apps.store.models import Product
            kwargs['queryset'] = Product.objects.filter(is_active=True).order_by('product_type', '-created_at')
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    @admin.display(description='Picture')
    def preview(self, obj):
        from django.utils.html import format_html
        d = obj.display()
        url = d['side'] or d['bg']
        if not url:
            return '—'
        return format_html('<img src="{}" alt="" style="height:54px;width:auto;max-width:96px;object-fit:cover;border-radius:3px">', url)

    @admin.display(description='Title')
    def slide_title(self, obj):
        return obj.display()['title'] or '—'

    @admin.display(description='Showing')
    def schedule(self, obj):
        from django.utils import timezone
        now = timezone.now()
        if not obj.is_active:
            return 'Off'
        if obj.starts_at and obj.starts_at > now:
            return f'From {timezone.localtime(obj.starts_at):%d %b %H:%M}'
        if obj.ends_at and obj.ends_at < now:
            return 'Ended'
        return f'Until {timezone.localtime(obj.ends_at):%d %b %H:%M}' if obj.ends_at else 'Now'
