from __future__ import annotations

from django import forms

from apps.alumni.recognition.models import (
    Broadcast,
    BroadcastAudience,
    SpotlightCategory,
)
from apps.core.countries import CountryChoiceField


class EndorsementForm(forms.Form):
    category = forms.ChoiceField(choices=SpotlightCategory.choices)
    period_label = forms.CharField(max_length=16)
    citation = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 3, "class": "field-input"}),
        max_length=400,
    )


class SpotlightPublishForm(forms.Form):
    profile_pk = forms.IntegerField(widget=forms.HiddenInput())
    category = forms.ChoiceField(choices=SpotlightCategory.choices)
    period_label = forms.CharField(max_length=16)
    title = forms.CharField(max_length=200)
    citation = forms.CharField(widget=forms.Textarea(attrs={"rows": 5, "class": "field-input"}))
    featured_from = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))
    featured_until = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))
    cover_image = forms.FileField(required=False)
    nominated_by_pk = forms.IntegerField(required=False, widget=forms.HiddenInput())

    def clean(self):
        data = super().clean()
        ff = data.get("featured_from")
        fu = data.get("featured_until")
        if ff and fu and fu < ff:
            raise forms.ValidationError("featured_until must be on or after featured_from.")
        return data


class BroadcastForm(forms.ModelForm):
    """Compose form for an officer-authored alumni broadcast."""

    country = CountryChoiceField(required=False, help_text="Search and select a country.")
    graduation_year = forms.IntegerField(required=False, min_value=1900, max_value=2100)
    programme_name = forms.CharField(required=False, max_length=255)
    group_ids = forms.CharField(
        required=False,
        help_text="Comma-separated NetworkGroup IDs (used when audience = by_group).",
    )

    class Meta:
        model = Broadcast
        fields = ["subject", "body_html", "audience", "scheduled_for"]
        widgets = {
            "body_html": forms.Textarea(
                attrs={
                    "rows": 12,
                    "class": "js-quill",
                    "data-quill-toolbar": "full",
                    "placeholder": "Write the announcement body — supports rich text.",
                }
            ),
            "scheduled_for": forms.DateTimeInput(attrs={"type": "datetime-local"}),
        }

    def clean(self):
        cleaned = super().clean()
        audience = cleaned.get("audience")
        af = {}
        if audience == BroadcastAudience.BY_COUNTRY:
            # CountryChoiceField already canonicalises to the full name ("Uganda").
            country = (cleaned.get("country") or "").strip()
            if not country:
                raise forms.ValidationError("Country is required for the 'by country' audience.")
            af["country"] = country
        elif audience == BroadcastAudience.BY_GRADUATION_YEAR:
            year = cleaned.get("graduation_year")
            if not year:
                raise forms.ValidationError("Graduation year is required for that audience.")
            af["graduation_year"] = int(year)
        elif audience == BroadcastAudience.BY_PROGRAMME:
            programme = (cleaned.get("programme_name") or "").strip()
            if not programme:
                raise forms.ValidationError("Programme name is required for that audience.")
            af["programme_name"] = programme
        elif audience == BroadcastAudience.BY_GROUP:
            raw = (cleaned.get("group_ids") or "").strip()
            ids = [int(x) for x in raw.replace(" ", "").split(",") if x.isdigit()]
            if not ids:
                raise forms.ValidationError("Provide at least one group ID for that audience.")
            af["group_ids"] = ids
        cleaned["audience_filter"] = af
        return cleaned
