from django import forms
from django.contrib import admin, messages
from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple
from django.core.exceptions import PermissionDenied
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.urls import path
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from .models import Catalog, Category, Author, Publisher, DistributionPackage, AuthorApplication, AuthorApplicationBook, LegacyAuthorInvitation, RightsType, Book, BookRight, CartItem, Order, OrderItem, Payment, Language, Format, EBookPlatform, BookPlatformLink, Currency, HomePageContent, Service, FounderParagraph, FounderAchievement, RightsAgencyFeature, Testimonial, ContactSubmission, FooterQuickLink, FooterServiceItem, NavigationItem, Subscriber
from .services.author_application_service import approve_application, reject_application
from .services.notification_service import notify_author_of_approval, notify_author_of_legacy_approval
from .services.legacy_invitation_service import (
    create_invitation, send_invitation_email, approve_invitation, reject_invitation,
)
from inventory.services import pdf_service

# In your_app/admin.py

admin.site.site_header = 'Tai AfroPress Admin'
admin.site.index_title = 'Book Management'
admin.site.site_title = 'Tai AfroPress Admin Portal'


def _is_finance(user) -> bool:
    """Staff who may see payment/banking details and review author applications."""
    return user.is_superuser or user.groups.filter(name="finance_managers").exists()


# Shared across AuthorAdmin and AuthorApplicationAdmin — all fields from
# PaymentDetailsMixin. Which ones are actually meaningful depends on
# payment_method; showing them all here (rather than a JS-conditional
# subset) keeps the admin simple and lets staff see whatever was filled in
# regardless of method.
_PAYMENT_FIELDSET_FIELDS = (
    'payment_method', 'payment_account_name', 'payment_reference', 'payment_phone',
    'payment_email', 'payment_details_confirmed',
    'bank_name', 'bank_account_number', 'bank_branch', 'bank_branch_code', 'bank_account_type',
    'bank_swift_code', 'bank_address', 'recipient_address', 'payment_currency', 'intermediary_bank_details',
    'paybill_number', 'paybill_account_number',
    'till_number',
)


admin.site.register(Catalog)
admin.site.register(Category)
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
    list_display  = ('name', 'email', 'default_my_keep_percent')
    search_fields = ('name', 'email')

    def get_fieldsets(self, request, obj=None):
        fieldsets = [
            (None, {'fields': ('name', 'email', 'address', 'id_number', 'bio', 'image')}),
            ('Margin Defaults', {
                'description': 'Applied to all books by this author unless overridden per-book.',
                'fields': ('default_my_keep_percent',),
            }),
        ]
        if _is_finance(request.user):
            fieldsets.append(
                ('Payment Details', {
                    'description': 'Where this author is paid — visible to finance staff only.',
                    'fields': _PAYMENT_FIELDSET_FIELDS,
                }),
            )
        return fieldsets


@admin.register(Publisher)
class PublisherAdmin(admin.ModelAdmin):
    list_display  = ('name', 'email', 'default_my_keep_percent')
    search_fields = ('name', 'email')
    fieldsets = (
        (None, {'fields': ('name', 'email')}),
        ('Margin Defaults', {
            'description': (
                'Applied to all books from this publisher unless overridden per-book. '
                'When a book has a publisher set, earnings and statements go to the '
                'publisher instead of the book\'s author.'
            ),
            'fields': ('default_my_keep_percent',),
        }),
    )


@admin.register(DistributionPackage)
class DistributionPackageAdmin(admin.ModelAdmin):
    list_display   = (
        'name', 'tier', 'my_keep_percent', 'allows_external_bookstores',
        'external_bookstore_author_percent',
        'book_signings_included', 'includes_social_media_management', 'is_featured', 'is_active',
    )
    list_editable  = ('is_featured', 'is_active')
    ordering       = ('tier',)
    fieldsets = (
        (None, {'fields': ('name', 'tier', 'description', 'is_featured', 'is_active')}),
        ('Terms', {
            'description': 'Drives what gets set on the Author record when an application on this package is approved, '
                            'and the terms auto-listed at Tai Bookstore/website and (if allowed) external bookstores.',
            'fields': (
                'my_keep_percent', 'allows_external_bookstores', 'external_bookstore_author_percent',
                'book_signings_included', 'includes_social_media_management',
            ),
        }),
    )


class AuthorApplicationBookInline(admin.TabularInline):
    model   = AuthorApplicationBook
    extra   = 0
    fields  = ('title', 'isbn', 'category', 'catalog', 'publication_year', 'selling_price_kes', 'copies_to_deliver', 'cover', 'created_book')
    readonly_fields = ('created_book',)

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

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


@admin.register(AuthorApplication)
class AuthorApplicationAdmin(admin.ModelAdmin):
    list_display    = ('full_name', 'package', 'email', 'status_badge', 'created_at', 'review_link', 'pdf_link')
    list_filter     = ('status', 'package')
    search_fields   = ('full_name', 'email')
    date_hierarchy  = 'created_at'
    inlines         = [AuthorApplicationBookInline]
    readonly_fields = (
        'status', 'signed_name', 'signed_at', 'signed_ip_address', 'agreement_text_snapshot',
        'reviewed_by', 'reviewed_at', 'created_author',
    )
    ordering = ('-created_at',)

    def has_add_permission(self, request):
        return False  # applications only ever come from the public API

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

    def get_fieldsets(self, request, obj=None):
        fieldsets = [
            (None, {'fields': ('package', 'full_name', 'email', 'phone', 'address', 'id_number', 'bio', 'status')}),
        ]
        if _is_finance(request.user):
            fieldsets.append(
                ('Payment Details', {
                    'description': 'Visible to finance staff only.',
                    'fields': _PAYMENT_FIELDSET_FIELDS,
                }),
            )
        fieldsets += [
            ('Signature', {
                'fields': ('signed_name', 'signed_at', 'signed_ip_address', 'agreement_text_snapshot'),
                'classes': ('collapse',),
            }),
            ('Review', {'fields': ('reviewed_by', 'reviewed_at', 'rejection_reason', 'created_author')}),
        ]
        return fieldsets

    @admin.display(description="Status")
    def status_badge(self, obj):
        colors = {
            AuthorApplication.STATUS_PENDING:  ("#B8860B", "#FFF8E1"),
            AuthorApplication.STATUS_APPROVED: ("#1B5E20", "#E8F5E9"),
            AuthorApplication.STATUS_REJECTED: ("#B71C1C", "#FFEBEE"),
        }
        color, bg = colors.get(obj.status, ("#555", "#eee"))
        return format_html(
            '<span style="color:{};background:{};padding:2px 8px;border-radius:3px;'
            'font-size:11px;font-weight:bold">{}</span>',
            color, bg, obj.get_status_display(),
        )

    @admin.display(description="")
    def review_link(self, obj):
        if obj.status != AuthorApplication.STATUS_PENDING:
            return "—"
        return format_html('<a href="{}/review/" style="font-weight:bold">Review →</a>', obj.pk)

    @admin.display(description="")
    def pdf_link(self, obj):
        return format_html('<a href="{}/pdf/" target="_blank">View as PDF</a>', obj.pk)

    def get_urls(self):
        custom = [
            path(
                "<int:pk>/review/",
                self.admin_site.admin_view(self.review_view),
                name="catalog_app_authorapplication_review",
            ),
            path(
                "<int:pk>/pdf/",
                self.admin_site.admin_view(self.pdf_view),
                name="catalog_app_authorapplication_pdf",
            ),
        ]
        return custom + super().get_urls()

    def pdf_view(self, request, pk):
        # The rendered agreement text (Appendix B) includes full banking/
        # M-Pesa details, so this follows the same finance-only gate as the
        # Payment Details fieldset on the change form and review page.
        if not _is_finance(request.user):
            raise PermissionDenied
        application = get_object_or_404(AuthorApplication, pk=pk)
        context = {"application": application, "generated_at": timezone.now()}
        filename = f"application-{application.full_name.replace(' ', '-')}-{application.pk}.pdf"
        return pdf_service.render_pdf("catalog_app/pdf/author_application.html", context, filename)

    def review_view(self, request, pk):
        application = get_object_or_404(AuthorApplication, pk=pk)
        can_review = _is_finance(request.user)
        error = None

        if request.method == "POST" and can_review:
            action = request.POST.get("action")

            if application.status != AuthorApplication.STATUS_PENDING:
                messages.error(request, "This application has already been reviewed.")
                return redirect("..")

            if action == "approve":
                for book in application.books.all():
                    catalog_id = request.POST.get(f"catalog_{book.pk}") or None
                    if str(book.catalog_id or "") != str(catalog_id or ""):
                        book.catalog_id = catalog_id
                        book.save(update_fields=["catalog"])
                try:
                    author = approve_application(application=application, user=request.user)
                    emailed = notify_author_of_approval(application)
                    messages.success(
                        request,
                        f"Approved — {author.name} and {application.books.count()} book(s) created "
                        f"(hidden from the site until stock is received and approved).",
                    )
                    if not emailed:
                        messages.warning(
                            request,
                            "Approval succeeded, but the agreement email to the author could not be "
                            "sent — check the server logs and resend manually if needed.",
                        )
                    return redirect("../../")
                except ValueError as exc:
                    error = str(exc)
            elif action == "reject":
                reason = request.POST.get("rejection_reason", "").strip()
                if not reason:
                    error = "Please provide a rejection reason."
                else:
                    reject_application(application=application, reason=reason, user=request.user)
                    messages.success(request, "Application rejected.")
                    return redirect("../../")

        context = {
            **self.admin_site.each_context(request),
            "title": f"Review Application: {application.full_name}",
            "opts": self.model._meta,
            "application": application,
            "can_review": can_review,
            "error": error,
            "catalogs": Catalog.objects.all() if can_review else None,
        }
        return render(request, "admin/catalog_app/authorapplication/review.html", context)


def _legacy_author_widget():
    return AutocompleteSelect(
        LegacyAuthorInvitation._meta.get_field("author"), admin.site,
        attrs={"data-placeholder": "Type to search authors…"},
    )


def _legacy_books_widget():
    return AutocompleteSelectMultiple(
        LegacyAuthorInvitation._meta.get_field("books"), admin.site,
        attrs={"data-placeholder": "Type to search books by title/ISBN…"},
    )


class LegacyInvitationForm(forms.Form):
    author = forms.ModelChoiceField(
        queryset=Author.objects.order_by("name"),
        widget=_legacy_author_widget(),
        help_text="The existing author to invite.",
    )
    books = forms.ModelMultipleChoiceField(
        queryset=Book.objects.order_by("title"),
        widget=_legacy_books_widget(),
        help_text="One or more of that author's existing books to cover under this agreement.",
    )
    author_email = forms.EmailField(
        required=False,
        label="Author's Email",
        help_text="Only needed if the selected author has no email on file — required in that case; "
                   "saved onto their record so it's there for next time too.",
    )

    def clean(self):
        cleaned = super().clean()
        author = cleaned.get("author")
        if author and not author.email and not cleaned.get("author_email"):
            self.add_error("author_email", "This author has no email on file — enter one to send the invitation.")
        return cleaned


@admin.register(LegacyAuthorInvitation)
class LegacyAuthorInvitationAdmin(admin.ModelAdmin):
    change_list_template = "admin/catalog_app/legacyauthorinvitation/change_list.html"
    list_display    = ("author", "books_list", "status_badge", "sent_at", "expires_at", "review_link", "resend_link")
    list_filter     = ("status",)
    search_fields   = ("author__name", "author__email")
    date_hierarchy  = "created_at"
    readonly_fields = (
        "author", "books", "package", "status", "signed_name", "signed_at", "signed_ip_address",
        "agreement_text_snapshot", "reviewed_by", "reviewed_at", "sent_at", "expires_at", "token",
    )
    ordering = ("-created_at",)

    def has_add_permission(self, request):
        return False  # invitations only ever come from the "Invite Author" flow

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

    def get_fieldsets(self, request, obj=None):
        fieldsets = [
            (None, {"fields": ("author", "books", "package", "status")}),
        ]
        if _is_finance(request.user):
            fieldsets.append(
                ("Payment Details", {
                    "description": "Visible to finance staff only.",
                    "fields": _PAYMENT_FIELDSET_FIELDS,
                }),
            )
        fieldsets += [
            ("Signature", {
                "fields": ("signed_name", "signed_at", "signed_ip_address", "agreement_text_snapshot"),
                "classes": ("collapse",),
            }),
            ("Invitation", {"fields": ("sent_at", "expires_at", "token")}),
            ("Review", {"fields": ("reviewed_by", "reviewed_at", "rejection_reason")}),
        ]
        return fieldsets

    @admin.display(description="Books")
    def books_list(self, obj):
        return ", ".join(obj.books.values_list("title", flat=True)) or "—"

    @admin.display(description="Status")
    def status_badge(self, obj):
        colors = {
            LegacyAuthorInvitation.STATUS_DRAFT:     ("#555", "#eee"),
            LegacyAuthorInvitation.STATUS_SENT:      ("#1565C0", "#E3F2FD"),
            LegacyAuthorInvitation.STATUS_SUBMITTED: ("#B8860B", "#FFF8E1"),
            LegacyAuthorInvitation.STATUS_APPROVED:  ("#1B5E20", "#E8F5E9"),
            LegacyAuthorInvitation.STATUS_REJECTED:  ("#B71C1C", "#FFEBEE"),
        }
        color, bg = colors.get(obj.status, ("#555", "#eee"))
        label = obj.get_status_display()
        if obj.status in (LegacyAuthorInvitation.STATUS_SENT,) and obj.is_expired:
            label = "Expired"
            color, bg = ("#B71C1C", "#FFEBEE")
        return format_html(
            '<span style="color:{};background:{};padding:2px 8px;border-radius:3px;'
            'font-size:11px;font-weight:bold">{}</span>',
            color, bg, label,
        )

    @admin.display(description="")
    def review_link(self, obj):
        if obj.status != LegacyAuthorInvitation.STATUS_SUBMITTED:
            return "—"
        return format_html('<a href="{}/review/" style="font-weight:bold">Review →</a>', obj.pk)

    @admin.display(description="")
    def resend_link(self, obj):
        # DRAFT included: send_invitation_email() leaves an invitation stuck
        # in DRAFT (never advances to SENT) when it fails before actually
        # sending — e.g. the author had no email on file — so Resend needs
        # to stay available for those too, not just ones already SENT.
        if obj.status not in (LegacyAuthorInvitation.STATUS_DRAFT, LegacyAuthorInvitation.STATUS_SENT):
            return "—"
        return format_html('<a href="{}/resend/" style="font-weight:bold">Resend →</a>', obj.pk)

    def get_urls(self):
        custom = [
            path("invite/", self.admin_site.admin_view(self.invite_view), name="catalog_app_legacyauthorinvitation_invite"),
            path("<int:pk>/review/", self.admin_site.admin_view(self.review_view), name="catalog_app_legacyauthorinvitation_review"),
            path("<int:pk>/resend/", self.admin_site.admin_view(self.resend_view), name="catalog_app_legacyauthorinvitation_resend"),
            path("<int:pk>/pdf/", self.admin_site.admin_view(self.pdf_view), name="catalog_app_legacyauthorinvitation_pdf"),
        ]
        return custom + super().get_urls()

    def invite_view(self, request):
        if request.method == "POST":
            form = LegacyInvitationForm(request.POST)
            if form.is_valid():
                author = form.cleaned_data["author"]
                if not author.email and form.cleaned_data.get("author_email"):
                    author.email = form.cleaned_data["author_email"]
                    author.save(update_fields=["email"])
                invitation = create_invitation(
                    author=author,
                    books=form.cleaned_data["books"],
                    user=request.user,
                )
                sent = send_invitation_email(invitation)
                if sent:
                    messages.success(request, f"Invitation created and emailed to {invitation.author.name}.")
                else:
                    messages.warning(
                        request,
                        f"Invitation created for {invitation.author.name}, but the email could not be sent "
                        f"(no email on file, or a delivery error — see the System Log). Use Resend once fixed.",
                    )
                return redirect("..")
        else:
            form = LegacyInvitationForm()

        context = {
            **self.admin_site.each_context(request),
            "title": "Invite Existing Author to Sign Agreement",
            "opts": self.model._meta,
            "form": form,
            "media": self.media + form.media,
        }
        return render(request, "admin/catalog_app/legacyauthorinvitation/invite.html", context)

    def resend_view(self, request, pk):
        invitation = get_object_or_404(LegacyAuthorInvitation, pk=pk)
        if invitation.status not in (LegacyAuthorInvitation.STATUS_DRAFT, LegacyAuthorInvitation.STATUS_SENT):
            messages.error(request, "Only a draft or sent (not yet submitted) invitation can be resent.")
            return redirect("../../")

        author = invitation.author
        error = None

        if request.method == "POST":
            email = (request.POST.get("author_email") or "").strip()
            if not author.email and not email:
                error = "This author has no email on file — enter one to send the invitation."
            else:
                if not author.email and email:
                    author.email = email
                    author.save(update_fields=["email"])
                sent = send_invitation_email(invitation)
                if sent:
                    messages.success(request, f"Signing link resent to {invitation.author.name}.")
                    return redirect("../../")
                else:
                    messages.error(request, "Could not send the email — details are in the System Log.")
                    return redirect("../../")

        context = {
            **self.admin_site.each_context(request),
            "title": f"Resend Signing Link: {invitation.author.name}",
            "opts": self.model._meta,
            "invitation": invitation,
            "error": error,
        }
        return render(request, "admin/catalog_app/legacyauthorinvitation/resend_confirm.html", context)

    def pdf_view(self, request, pk):
        if not _is_finance(request.user):
            raise PermissionDenied
        from .services.legacy_invitation_service import _LegacyAgreementView

        invitation = get_object_or_404(LegacyAuthorInvitation, pk=pk)
        view = _LegacyAgreementView(invitation)
        context = {"application": view, "generated_at": timezone.now()}
        filename = f"legacy-invitation-{invitation.author.name.replace(' ', '-')}-{invitation.pk}.pdf"
        return pdf_service.render_pdf("catalog_app/pdf/author_application.html", context, filename)

    def review_view(self, request, pk):
        invitation = get_object_or_404(LegacyAuthorInvitation, pk=pk)
        can_review = _is_finance(request.user)
        error = None

        if request.method == "POST" and can_review:
            action = request.POST.get("action")

            if invitation.status != LegacyAuthorInvitation.STATUS_SUBMITTED:
                messages.error(request, "This invitation has already been reviewed.")
                return redirect("..")

            if action == "approve":
                try:
                    author = approve_invitation(invitation=invitation, user=request.user)
                    emailed = notify_author_of_legacy_approval(invitation)
                    messages.success(
                        request,
                        f"Approved — {author.name}'s default margin is now set from the "
                        f"{invitation.package.name} package, applying to all their books going forward.",
                    )
                    if not emailed:
                        messages.warning(
                            request,
                            "Approval succeeded, but the agreement email to the author could not be "
                            "sent — check the server logs and resend manually if needed.",
                        )
                    return redirect("../../")
                except ValueError as exc:
                    error = str(exc)
            elif action == "reject":
                reason = request.POST.get("rejection_reason", "").strip()
                if not reason:
                    error = "Please provide a rejection reason."
                else:
                    reject_invitation(invitation=invitation, reason=reason, user=request.user)
                    messages.success(request, "Invitation rejected.")
                    return redirect("../../")

        context = {
            **self.admin_site.each_context(request),
            "title": f"Review Legacy Agreement: {invitation.author.name}",
            "opts": self.model._meta,
            "invitation": invitation,
            "can_review": can_review,
            "error": error,
            "book_edits": invitation.book_edits.select_related("book"),
        }
        return render(request, "admin/catalog_app/legacyauthorinvitation/review.html", context)


admin.site.register(RightsType)

class BookPlatformLinkInline(admin.TabularInline):
    model = BookPlatformLink
    extra = 1

class BookAdminForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["price"].required = True
        self.fields["old_price"].required = False


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    form = BookAdminForm
    inlines = [BookPlatformLinkInline]
    list_display  = ('title', 'author', 'publisher', 'category', 'selling_price_kes', 'my_keep_percent', 'track_inventory', 'is_featured', 'is_listed')
    list_filter   = ('is_featured', 'is_listed', 'track_inventory', 'category', 'publication_year', 'author', 'publisher')
    search_fields = ('title', 'subtitle', 'isbn', 'author__name', 'publisher__name')
    list_select_related = ('author', 'publisher', 'category')
    readonly_fields = ('stock',)

    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        if obj.pos_price is not None:
            from inventory.services.inventory_service import ensure_internal_listing_for_book
            ensure_internal_listing_for_book(obj, user=request.user)

    fieldsets = (
        (None, {
            'fields': ('catalog', 'author', 'publisher', 'category', 'title', 'subtitle', 'description', 'cover',
                       'publication_year', 'isbn', 'is_featured', 'is_listed'),
            'description': (
                'publisher: leave blank if you work directly with the author. If set, '
                'earnings and monthly statements for this book go to the publisher instead '
                'of the author (the author is still shown for credit).'
            ),
        }),
        ('Pricing', {
            'fields': ('price', 'old_price', 'currency', 'selling_price_kes', 'pos_price'),
            'description': (
                'selling_price_kes is the original agreed price — reporting and the author\'s '
                'payout always stay pinned to it. old_price shows a strikethrough sale price on '
                'the storefront when set. pos_price is an optional markup charged at Tai '
                'Bookstore/website only; the difference goes to platform profit, never the author.'
            ),
        }),
        ('Ratings', {
            'fields': ('rating', 'review_count'),
            'description': 'Shown as star ratings on the storefront. Leave rating blank to hide stars for this book.',
        }),
        ('Formats & Languages', {
            'fields': ('available_languages', 'available_formats'),
            'classes': ('collapse',),
        }),
        ('Inventory & Margins', {
            'fields': ('track_inventory', 'stock', 'reorder_level', 'my_keep_percent'),
            'description': (
                'Stock is read-only and updated automatically from inventory transactions. '
                'To add or adjust stock go to Inventory → Receive Stock (or Transfer / Adjust). '
                'my_keep_percent: leave blank to use the author\'s default margin. '
                'reorder_level: low-stock alert threshold.'
            ),
        }),
    )

admin.site.register(BookRight)
admin.site.register(CartItem)
admin.site.register(Order)
admin.site.register(OrderItem)
admin.site.register(Payment)
admin.site.register(Language)
admin.site.register(Format)
admin.site.register(Currency)
admin.site.register(EBookPlatform)

class NavigationItemInline(admin.TabularInline):
    model = NavigationItem
    extra = 1

class ServiceInline(admin.TabularInline):
    model = Service
    extra = 1

class FounderParagraphInline(admin.TabularInline):
    model = FounderParagraph
    extra = 1

class FounderAchievementInline(admin.TabularInline):
    model = FounderAchievement
    extra = 1

class RightsAgencyFeatureInline(admin.TabularInline):
    model = RightsAgencyFeature
    extra = 1

class TestimonialInline(admin.TabularInline):
    model = Testimonial
    extra = 1

class FooterQuickLinkInline(admin.TabularInline):
    model = FooterQuickLink
    extra = 1

class FooterServiceItemInline(admin.TabularInline):
    model = FooterServiceItem
    extra = 1

@admin.register(HomePageContent)
class HomePageContentAdmin(admin.ModelAdmin):
    list_display = ('title', 'is_active', 'updated_at')
    list_filter = ('is_active',)
    search_fields = ('title', 'subtitle')
    change_form_template = "admin/catalog_app/homepagecontent/change_form.html"
    inlines = [NavigationItemInline, ServiceInline, FounderParagraphInline, FounderAchievementInline, RightsAgencyFeatureInline, TestimonialInline, FooterQuickLinkInline, FooterServiceItemInline]

@admin.register(ContactSubmission)
class ContactSubmissionAdmin(admin.ModelAdmin):
    list_display = ('email', 'subject', 'submitted_at')
    list_filter = ('submitted_at',)
    search_fields = ('first_name', 'last_name', 'email', 'subject', 'message')
    readonly_fields = ('first_name', 'last_name', 'email', 'subject', 'message', 'submitted_at')

    def has_add_permission(self, request):
        return False

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

@admin.register(Subscriber)
class SubscriberAdmin(admin.ModelAdmin):
    list_display = ('email', 'is_active', 'subscribed_at')
    list_filter = ('is_active', 'subscribed_at')
    search_fields = ('email',)
    readonly_fields = ('token',)

# Newsletter admin (composer, preview, test/bulk send) lives in
# admin_newsletter.py — imported below so its @admin.register(Newsletter) runs.
from . import admin_newsletter  # noqa: E402,F401
