from django import forms

from .models import ContactInquiry, Product


class ContactInquiryForm(forms.ModelForm):
    class Meta:
        model = ContactInquiry
        fields = [
            "product",
            "name",
            "email",
            "phone",
            "preferred_contact_method",
            "subject",
            "message",
        ]
        widgets = {
            "message": forms.Textarea(attrs={"rows": 5}),
        }
        labels = {
            "product": "Produkt / Kollektion",
            "name": "Ihr Name",
            "email": "E-Mail-Adresse",
            "phone": "Telefonnummer",
            "preferred_contact_method": "Bevorzugte Kontaktart",
            "subject": "Betreff",
            "message": "Nachricht",
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["product"].queryset = Product.objects.filter(is_active=True).select_related("category")
        self.fields["product"].required = False
        self.fields["product"].empty_label = "Allgemeine Beratung"

        placeholders = {
            "name": "z. B. Anna Becker",
            "email": "anna@example.com",
            "phone": "+49 ...",
            "subject": "z. B. Beratung zu Trauringen",
            "message": "Worum geht es? Teilen Sie uns kurz Ihre Wünsche mit.",
        }
        for name, field in self.fields.items():
            widget = field.widget
            css_class = "form-select" if isinstance(widget, forms.Select) else "form-control"
            existing = widget.attrs.get("class", "")
            widget.attrs["class"] = f"{existing} {css_class}".strip()
            if name in placeholders:
                widget.attrs["placeholder"] = placeholders[name]

    def clean(self):
        cleaned_data = super().clean()
        preferred_contact_method = cleaned_data.get("preferred_contact_method")
        phone = (cleaned_data.get("phone") or "").strip()
        product = cleaned_data.get("product")
        subject = (cleaned_data.get("subject") or "").strip()

        if preferred_contact_method == ContactInquiry.PreferredContactMethod.PHONE and not phone:
            self.add_error("phone", "Bitte geben Sie eine Telefonnummer an, wenn Sie einen Rückruf wünschen.")

        if product and not subject:
            cleaned_data["subject"] = f"Anfrage zu {product.name}"

        return cleaned_data
