from django import forms

from django.core.files.uploadedfile import UploadedFile
from django.db.models import Q

from apps.core.validators import validate_photo

from .models import Member, MemberCategory, Visitor


class MemberForm(forms.ModelForm):
    guardian_name = forms.CharField(label="Nom du tuteur", required=False, max_length=160)
    guardian_relation = forms.CharField(label="Lien de parenté", required=False, max_length=60)
    guardian_phone = forms.CharField(label="Téléphone du tuteur", required=False, max_length=32)

    class Meta:
        model = Member
        fields = ["category", "first_name", "last_name", "birth_date", "sex", "phone",
                  "phone_alt", "email", "address", "quarter", "city", "photo", "notes_internal"]
        widgets = {
            "birth_date": forms.DateInput(attrs={"type": "date"}),
            "notes_internal": forms.Textarea(attrs={"rows": 2}),
        }

    def __init__(self, agency, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.agency = agency
        self.fields["category"].queryset = MemberCategory.objects.filter(is_active=True).filter(
            Q(scope="NATIONAL") | Q(agency=agency)
        ).order_by("name_fr")
        if self.instance.pk and hasattr(self.instance, "guardian"):
            guardian = self.instance.guardian
            self.fields["guardian_name"].initial = guardian.full_name
            self.fields["guardian_relation"].initial = guardian.relation
            self.fields["guardian_phone"].initial = guardian.phone

    def clean_photo(self):
        photo = self.cleaned_data.get("photo")
        if isinstance(photo, UploadedFile):  # nouveau fichier uniquement
            validate_photo(photo)
        return photo

    def clean(self):
        data = super().clean()
        category = data.get("category")
        birthday = data.get("birth_date")
        if category and category.requires_guardian:
            if not data.get("guardian_name") or not data.get("guardian_phone"):
                raise forms.ValidationError("Cette catégorie exige le nom et le téléphone d'un tuteur.")
        if birthday:
            from datetime import date
            age = date.today().year - birthday.year - ((date.today().month, date.today().day) < (birthday.month, birthday.day))
            if age < 18 and not data.get("guardian_name"):
                raise forms.ValidationError("Un membre mineur doit avoir un tuteur identifié.")
        return data


class VisitorForm(forms.ModelForm):
    class Meta:
        model = Visitor
        fields = ["first_name", "last_name", "phone", "email", "organization", "id_type", "id_number"]


class VisitForm(forms.Form):
    purpose = forms.CharField(label="Motif de la visite", max_length=160)
    person_to_see = forms.CharField(label="Personne visitée", max_length=160, required=False)
