from django import forms

from .models import JobPosting, JobSource


class StyledModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            widget = field.widget
            if isinstance(widget, forms.CheckboxInput):
                widget.attrs.setdefault("class", "form-check-input")
            elif isinstance(widget, forms.Select):
                widget.attrs.setdefault("class", "form-select")
            else:
                widget.attrs.setdefault("class", "form-control")


class JobSourceForm(StyledModelForm):
    class Meta:
        model = JobSource
        fields = ["name", "family", "url", "status", "owner", "notes"]
        widgets = {
            "notes": forms.Textarea(attrs={"rows": 4}),
        }
        help_texts = {
            "url": "Paste the public job board, agency, or careers page URL.",
            "owner": "Optional teammate responsible for this connector.",
        }

    def clean_name(self):
        return self.cleaned_data["name"].strip()


class JobPostingForm(StyledModelForm):
    class Meta:
        model = JobPosting
        fields = [
            "source",
            "title",
            "company",
            "location",
            "contract_type",
            "remote",
            "salary",
            "apply_url",
            "published_at",
            "description",
            "is_active",
        ]
        widgets = {
            "published_at": forms.DateInput(attrs={"type": "date"}),
            "description": forms.Textarea(attrs={"rows": 6}),
        }
        help_texts = {
            "source": "Choose the connector/source that found this offer.",
            "description": "Paste a concise cleaned description; the pipeline view will evolve from here.",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["source"].queryset = JobSource.objects.order_by("family", "name")
        self.fields["source"].empty_label = "Select a source"

    def clean_title(self):
        return self.cleaned_data["title"].strip()

    def clean_company(self):
        return self.cleaned_data["company"].strip()
