from django import forms
from wagtail.admin.rich_text import DraftailRichTextArea

from .models import ContactFormSubmission, NewsletterCampaign, NewsletterTemplate


class NewsletterSubscribeForm(forms.Form):
    email = forms.EmailField(max_length=254)


class NewsletterUnsubscribeForm(forms.Form):
    email = forms.EmailField(
        max_length=254,
        required=False,
        widget=forms.EmailInput(
            attrs={
                "readonly": "readonly",
                "aria-readonly": "true",
            }
        ),
    )
    token = forms.CharField(max_length=1024, widget=forms.HiddenInput())


class ContactForm(forms.ModelForm):
    class Meta:
        model = ContactFormSubmission
        fields = ["name", "contact", "email", "category", "message", "source_page"]
        widgets = {
            "source_page": forms.HiddenInput(),
        }


class NewsletterHtmlEditorWidget(forms.Textarea):
    class Media:
        js = ("js/newsletter_template_editor.js",)
        css = {
            "all": ("css/newsletter_template_editor.css",)
        }

    def render(self, name, value, attrs=None, renderer=None):
        attrs = attrs or {}
        attrs["data-newsletter-html-input"] = "1"
        attrs.setdefault("spellcheck", "false")
        return super().render(name, value, attrs, renderer)


class NewsletterCampaignEditorWidget(DraftailRichTextArea):
    class Media:
        js = ("js/newsletter_campaign_editor.js",)
        css = {"all": ("css/newsletter_campaign_editor.css",)}

    def render(self, name, value, attrs=None, renderer=None):
        return super().render(name, value, attrs, renderer)


class NewsletterTemplateAdminForm(forms.ModelForm):
    class Meta:
        model = NewsletterTemplate
        fields = ["name", "subject", "template_html", "template_text"]
        widgets = {
            "template_html": NewsletterHtmlEditorWidget(
                attrs={
                    "rows": 28,
                    "placeholder": "Use {{email_body}} as the content placeholder.",
                }
            ),
            "template_text": forms.Textarea(
                attrs={
                    "rows": 8,
                    "placeholder": "Use {{email_body}} as the content placeholder.",
                }
            ),
        }


class NewsletterCampaignAdminForm(forms.ModelForm):
    class Media:
        js = ("js/newsletter_campaign_editor.js",)
        css = {"all": ("css/newsletter_campaign_editor.css",)}

    class Meta:
        model = NewsletterCampaign
        fields = [
            "title",
            "campaign_type",
            "newsletter_template",
            "list_id",
            "subject_template",
            "html_template",
            "text_template",
            "weekly_articles",
            "item_template_html",
            "scheduled_at",
        ]
        widgets = {
            "html_template": NewsletterCampaignEditorWidget(
                features=["h2", "h3", "bold", "italic", "link", "image", "ul", "ol"],
            ),
            "weekly_articles": forms.CheckboxSelectMultiple(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        from home.models import ArticlePage

        self.fields["weekly_articles"].queryset = ArticlePage.objects.live().order_by("-date", "-id")
        self.fields["weekly_articles"].help_text = "每週新聞類型請勾選要帶入的文章（可多選）。"
        self.fields["campaign_type"].required = True
        # Required constraints are enforced by campaign type in clean()
        self.fields["html_template"].required = False
        self.fields["text_template"].required = False
        self.fields["weekly_articles"].required = False
        self.fields["item_template_html"].required = False
        if self.instance and self.instance.pk:
            self.fields["campaign_type"].disabled = True

    def clean(self):
        cleaned = super().clean()
        campaign_type = cleaned.get("campaign_type")
        if self.instance and self.instance.pk:
            campaign_type = self.instance.campaign_type
        articles = cleaned.get("weekly_articles")
        if campaign_type == NewsletterCampaign.TYPE_WEEKLY_NEWS and not articles:
            self.add_error("weekly_articles", "每週新聞電子報至少要選擇一篇文章。")
        if campaign_type == NewsletterCampaign.TYPE_WEEKLY_NEWS:
            cleaned["html_template"] = "<p></p>"
        if campaign_type != NewsletterCampaign.TYPE_WEEKLY_NEWS and not (cleaned.get("html_template") or "").strip():
            self.add_error("html_template", "一般電子報需要填寫內容。")
        return cleaned

    def save(self, commit=True):
        obj = super().save(commit=False)
        selected = self.cleaned_data.get("weekly_articles") or []
        if obj.campaign_type == NewsletterCampaign.TYPE_WEEKLY_NEWS:
            obj.html_template = "<p></p>"
            obj.content_config = {
                **(obj.content_config or {}),
                "article_page_ids": [int(p.pk) for p in selected],
            }
        else:
            obj.content_config = {}
            obj.item_template_html = obj.item_template_html or ""
        if commit:
            obj.save()
            self.save_m2m()
        return obj
