from __future__ import annotations

from django import forms
from django.forms import inlineformset_factory

from apps.alumni.profiles.models import (
    AlumniCertificate,
    AlumniProfile,
    Degree,
    Employment,
    Publication,
)
from apps.core.countries import CountryChoiceField


class ProfileEditForm(forms.ModelForm):
    class Meta:
        model = AlumniProfile
        fields = [
            "current_employer",
            "current_position",
            "current_institution",
            "orcid_id",
            "linkedin_url",
            "twitter_url",
            "website_url",
            "researchgate_url",
            "photo",
            "headline",
            "expertise_tags",
            "mentor_accepting",
            "mentor_topics",
            "mentor_capacity",
            "mentor_statement",
        ]
        widgets = {
            "headline": forms.TextInput(),
            "expertise_tags": forms.TextInput(
                attrs={
                    "placeholder": "agronomy, policy, gender",
                    "autocomplete": "off",
                }
            ),
            "mentor_topics": forms.TextInput(
                attrs={
                    "placeholder": "publishing, fundraising, policy engagement",
                    "autocomplete": "off",
                }
            ),
            "mentor_capacity": forms.NumberInput(attrs={"min": 1, "max": 20}),
            "mentor_statement": forms.Textarea(
                attrs={
                    "rows": 3,
                    "placeholder": "Short message to prospective mentees — your style, what you offer.",
                }
            ),
            "linkedin_url": forms.URLInput(attrs={"placeholder": "https://linkedin.com/in/…"}),
            "twitter_url": forms.URLInput(attrs={"placeholder": "https://twitter.com/…"}),
            "website_url": forms.URLInput(attrs={"placeholder": "https://…"}),
            "researchgate_url": forms.URLInput(attrs={"placeholder": "https://researchgate.net/…"}),
        }

    def _normalise_tags(self, value) -> list[str]:
        if isinstance(value, list):
            return [str(t).strip().lower() for t in value if str(t).strip()]
        if isinstance(value, str):
            return [t.strip().lower() for t in value.split(",") if t.strip()]
        return []

    def clean_expertise_tags(self):
        return self._normalise_tags(self.cleaned_data.get("expertise_tags") or [])

    def clean_mentor_topics(self):
        return self._normalise_tags(self.cleaned_data.get("mentor_topics") or [])

    def clean_orcid_id(self):
        value = (self.cleaned_data.get("orcid_id") or "").strip()
        if not value:
            return ""
        # ORCID format: 0000-0000-0000-000X (X can be digit or 'X').
        parts = value.split("-")
        if len(parts) != 4 or not all(len(p) == 4 for p in parts):
            raise forms.ValidationError(
                "ORCID iD must be four groups of four separated by dashes."
            )
        return value


class DegreeForm(forms.ModelForm):
    class Meta:
        model = Degree
        fields = [
            "institution",
            "programme_name",
            "degree_type",
            "started_on",
            "graduated_on",
            "thesis_title",
            "advisor_name",
            "funder",
        ]
        widgets = {
            "started_on": forms.DateInput(attrs={"type": "date"}),
            "graduated_on": forms.DateInput(attrs={"type": "date"}),
        }


class EmploymentForm(forms.ModelForm):
    country = CountryChoiceField(required=False)

    class Meta:
        model = Employment
        fields = [
            "organisation",
            "position",
            "sector",
            "country",
            "started_on",
            "ended_on",
            "description",
        ]
        widgets = {
            "started_on": forms.DateInput(attrs={"type": "date"}),
            "ended_on": forms.DateInput(attrs={"type": "date"}),
            "description": forms.Textarea(
                attrs={
                    "rows": 4,
                    "class": "js-quill",
                    "data-quill-toolbar": "compact",
                    "placeholder": "Responsibilities, achievements, highlights…",
                }
            ),
        }


class PublicationForm(forms.ModelForm):
    class Meta:
        model = Publication
        fields = [
            "title",
            "authors_text",
            "publication_type",
            "doi",
            "url",
            "year",
            "document",
        ]
        widgets = {
            "authors_text": forms.Textarea(attrs={"rows": 2}),
            "doi": forms.TextInput(attrs={"placeholder": "10.xxxx/yyyy"}),
            "url": forms.URLInput(attrs={"placeholder": "https://…"}),
            # The repository document is chosen via the HTMX search widget in
            # the publications editor; the id rides along in this hidden input.
            "document": forms.HiddenInput(),
        }

    def save(self, commit=True):
        """Keep ``cited_in_repository`` in lock-step with the linked document.

        The publications editor sets ``document`` through the repository search
        widget; whenever a document is attached we flag the publication as cited
        in the IILMP repository (and clear the flag when it is unlinked), so the
        indicator on the public profile always matches reality.
        """
        obj = super().save(commit=False)
        obj.cited_in_repository = obj.document_id is not None
        if commit:
            obj.save()
        return obj


class AlumniCertificateForm(forms.ModelForm):
    class Meta:
        model = AlumniCertificate
        fields = [
            "title",
            "issuer",
            "issued_on",
            "file",
            "verification_url",
        ]
        widgets = {
            "issued_on": forms.DateInput(attrs={"type": "date"}),
            "verification_url": forms.URLInput(attrs={"placeholder": "https://…"}),
        }


class VisibilityForm(forms.ModelForm):
    class Meta:
        model = AlumniProfile
        fields = ["visibility_consent"]


DegreeFormSet = inlineformset_factory(
    AlumniProfile,
    Degree,
    form=DegreeForm,
    extra=0,
    can_delete=True,
)

EmploymentFormSet = inlineformset_factory(
    AlumniProfile,
    Employment,
    form=EmploymentForm,
    extra=0,
    can_delete=True,
)

PublicationFormSet = inlineformset_factory(
    AlumniProfile,
    Publication,
    form=PublicationForm,
    extra=0,
    can_delete=True,
)

CertificateFormSet = inlineformset_factory(
    AlumniProfile,
    AlumniCertificate,
    form=AlumniCertificateForm,
    extra=0,
    can_delete=True,
)


class EmployerFeedbackRequestForm(forms.Form):
    """Form the alumna/us fills to invite an employer."""

    employer_email = forms.EmailField()
    employer_name = forms.CharField(max_length=255, required=False)


class EmployerFeedbackResponseForm(forms.Form):
    """Form the employer fills to give curriculum feedback.

    Submitted answers land on TracerResponse.payload — keep the schema
    explicit here so it round-trips cleanly through M&EL aggregation.
    """

    OUTCOME_RATINGS = [
        (5, "Very well prepared"),
        (4, "Well prepared"),
        (3, "Adequately prepared"),
        (2, "Some gaps"),
        (1, "Significant gaps"),
    ]
    role_title = forms.CharField(max_length=255, required=False, label="Role you're rating")
    employment_status = forms.ChoiceField(
        required=False,
        choices=[
            ("", "—"),
            ("full_time", "Full-time"),
            ("part_time", "Part-time"),
            ("contract", "Contract / consultant"),
            ("intern", "Intern"),
            ("other", "Other"),
        ],
    )
    preparedness = forms.TypedChoiceField(
        coerce=int,
        choices=OUTCOME_RATINGS,
        widget=forms.RadioSelect,
        label="How well did RUFORUM training prepare them?",
    )
    skills_strong = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 3}),
        label="Where do they excel?",
    )
    skills_gap = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 3}),
        label="Where would more training help?",
    )
    curriculum_suggestions = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={"rows": 3}),
        label="Curriculum suggestions for RUFORUM",
    )
    consent_named = forms.BooleanField(
        required=False,
        label="It is OK to share this feedback with universities, named.",
    )
