from django.urls import reverse
from django.utils.translation import gettext as _
from wagtail import hooks
from wagtail.admin.panels import FieldPanel
from wagtail.admin.rich_text import DraftailRichTextArea
from wagtail.admin.widgets import Button
from wagtail.permission_policies import ModelPermissionPolicy
from wagtail.snippets.models import register_snippet
from wagtail.snippets.views.snippets import CreateView, SnippetViewSet

from .models import NewsletterCampaign, NewsletterDispatchRecord, NewsletterSystemSettings


class NewsletterCampaignCreateView(CreateView):
    def get_initial(self):
        initial = super().get_initial()
        if (initial.get("list_id") or "").strip():
            return initial
        default_list_id = (NewsletterSystemSettings.load().member_center_list_id or "").strip()
        if default_list_id:
            initial["list_id"] = default_list_id
        return initial


class NewsletterCampaignViewSet(SnippetViewSet):
    model = NewsletterCampaign
    icon = "mail"
    menu_label = _("Newsletter campaigns")
    menu_order = 250
    add_to_admin_menu = True
    add_view_class = NewsletterCampaignCreateView
    list_display = ["title", "list_id", "status", "scheduled_at", "sent_at", "updated_at"]
    list_filter = ["status"]
    search_fields = ["title", "list_id", "subject_template"]
    panels = [
        FieldPanel("title"),
        FieldPanel(
            "list_id",
            help_text=_("Leave blank to use member_center_list_id from Newsletter System Settings."),
        ),
        FieldPanel("subject_template"),
        FieldPanel(
            "html_template",
            widget=DraftailRichTextArea(
                features=["h2", "h3", "bold", "italic", "link", "image", "ul", "ol"],
            ),
            help_text=_("Use image picker/upload from Wagtail. Prefer image URLs instead of Base64 in CMS."),
        ),
        FieldPanel("text_template"),
        FieldPanel("scheduled_at"),
    ]


class ReadOnlySnippetPermissionPolicy(ModelPermissionPolicy):
    def user_has_permission(self, user, action):
        if action in {"add", "change", "delete"}:
            return False
        return super().user_has_permission(user, action)


class NewsletterDispatchRecordViewSet(SnippetViewSet):
    model = NewsletterDispatchRecord
    icon = "tasks"
    menu_label = _("Newsletter dispatch records")
    menu_order = 251
    add_to_admin_menu = True
    inspect_view_enabled = True
    copy_view_enabled = False
    permission_policy = ReadOnlySnippetPermissionPolicy(NewsletterDispatchRecord)
    list_display = [
        "campaign",
        "email",
        "subscriber_id",
        "status",
        "retry_count",
        "next_retry_at",
        "response_status",
        "created_at",
    ]
    list_filter = ["status", "created_at"]
    search_fields = ["email", "subscriber_id", "campaign__title"]


register_snippet(NewsletterCampaignViewSet)
register_snippet(NewsletterDispatchRecordViewSet)


@hooks.register("register_snippet_listing_buttons")
def newsletter_campaign_listing_buttons(snippet, user, next_url=None):
    if not isinstance(snippet, NewsletterCampaign):
        return
    if not user.is_staff:
        return
    if snippet.status == NewsletterCampaign.STATUS_SENDING:
        return

    label = _("Send now")
    yield Button(
        label,
        reverse("newsletter_campaign_send_now", args=[snippet.pk]),
        icon_name="mail",
        priority=15,
    )
