from __future__ import annotations

from django import forms

from apps.alumni.profiles.models import AlumniProfile
from apps.alumni.tracking.models import CareerMilestone, ImpactRecord, ImpactSource


class MilestoneForm(forms.ModelForm):
    class Meta:
        model = CareerMilestone
        fields = [
            "milestone_type",
            "title",
            "description",
            "occurred_on",
            "url",
            "evidence_file",
            "visibility",
        ]
        widgets = {
            "occurred_on": forms.DateInput(attrs={"type": "date"}),
            "url": forms.URLInput(attrs={"placeholder": "https://…"}),
            "description": forms.Textarea(
                attrs={
                    "rows": 5,
                    "class": "js-quill",
                    "data-quill-toolbar": "compact",
                    "placeholder": "Two or three sentences of context — why it matters…",
                }
            ),
        }


class ImpactRecordForm(forms.ModelForm):
    """Staff data-entry form for a single donor-facing impact metric.

    ``source`` defaults to self-reported / manual — the seeder and ORCID
    sync own the other sources, so a hand-entered record is always manual.
    """

    class Meta:
        model = ImpactRecord
        fields = ["profile", "metric", "value", "period_label", "source"]
        widgets = {
            "period_label": forms.TextInput(attrs={"placeholder": "2026 or 2026-Q1"}),
            "value": forms.NumberInput(attrs={"step": "0.01", "min": "0"}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["profile"].queryset = AlumniProfile.objects.select_related(
            "user"
        ).order_by("user__first_name", "user__last_name")
        self.fields["profile"].label = "Alumnus / alumna"
        self.fields["source"].initial = ImpactSource.SELF
        self.fields["value"].help_text = (
            "Numeric value for the metric — USD for funding, a count for citations, etc."
        )


class ImpactSurveyLaunchForm(forms.Form):
    """Launch form for an alumni impact/tracer survey.

    Not a ModelForm — the Survey is created via
    ``apps.alumni.tracking.services_impact_survey.launch_impact_survey``,
    which owns question/audience construction. Cohort fields are all
    optional; leaving them blank targets every alumnus.
    """

    title = forms.CharField(
        max_length=255,
        initial="RUFORUM alumni tracer survey",
        widget=forms.TextInput(attrs={"placeholder": "e.g. 2026 alumni tracer survey"}),
    )
    description = forms.CharField(
        required=False,
        widget=forms.Textarea(
            attrs={
                "rows": 3,
                "placeholder": "Short note on why this cohort is being surveyed.",
            }
        ),
    )
    graduation_year = forms.IntegerField(
        required=False,
        min_value=1990,
        max_value=2100,
        widget=forms.NumberInput(attrs={"placeholder": "e.g. 2023"}),
        help_text="Optional — leave blank to include all graduation years.",
    )
    programme_name = forms.CharField(
        required=False,
        max_length=255,
        widget=forms.TextInput(attrs={"placeholder": "e.g. MSc Agricultural Economics"}),
        help_text="Optional — matches programme names containing this text.",
    )
    country = forms.CharField(
        required=False,
        max_length=100,
        widget=forms.TextInput(attrs={"placeholder": "e.g. Uganda"}),
        help_text="Optional — exact country match.",
    )
    use_standard_questions = forms.BooleanField(
        required=False,
        initial=True,
        label="Use the standard RUFORUM tracer questions",
        help_text=(
            "Employment status, sector, job title, income change, further "
            "study, training relevance rating, and an open impact story field."
        ),
    )

    def cohort_filter(self) -> dict:
        data = self.cleaned_data
        cohort: dict = {}
        if data.get("graduation_year"):
            cohort["graduation_year"] = data["graduation_year"]
        if data.get("programme_name"):
            cohort["programme_name"] = data["programme_name"].strip()
        if data.get("country"):
            cohort["country"] = data["country"].strip()
        return cohort
