import re

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User

from .models import Profile


class BootstrapMixin:
    """Add Bootstrap classes to form fields."""

    def _init_bootstrap(self):
        for name, field in self.fields.items():
            existing_classes = field.widget.attrs.get("class", "")
            field.widget.attrs["class"] = f"form-control {existing_classes}".strip()


class RegistrationForm(BootstrapMixin, UserCreationForm):
    first_name = forms.CharField(label="Имя", max_length=150)
    last_name = forms.CharField(label="Фамилия", max_length=150)
    phone = forms.CharField(label="Телефон", max_length=20)
    email = forms.EmailField(label="Email", required=False)

    class Meta:
        model = User
        fields = (
            "username",
            "first_name",
            "last_name",
            "phone",
            "email",
            "password1",
            "password2",
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._init_bootstrap()
        self.fields["phone"].widget.attrs.setdefault("placeholder", "+7XXXXXXXXXX")
        self.fields["phone"].widget.attrs.setdefault("inputmode", "tel")
        self.fields["username"].label = "Логин"
        for name in ["password1", "password2"]:
            self.fields[name].widget.attrs["autocomplete"] = "new-password"

    def clean_phone(self):
        raw = self.cleaned_data.get("phone", "")
        digits = "".join(ch for ch in raw if ch.isdigit())
        if digits.startswith("8"):
            digits = "7" + digits[1:]
        if not digits.startswith("7") or len(digits) != 11:
            raise forms.ValidationError("Введите реальный номер в формате +7XXXXXXXXXX")
        return f"+{digits}"

    def save(self, commit=True):
        user = super().save(commit=False)
        user.first_name = self.cleaned_data.get("first_name", "")
        user.last_name = self.cleaned_data.get("last_name", "")
        user.email = self.cleaned_data.get("email", "")
        if commit:
            user.save()
            Profile.objects.update_or_create(
                user=user, defaults={"phone": self.cleaned_data.get("phone", "")}
            )
        return user


class LoginForm(BootstrapMixin, AuthenticationForm):
    username = forms.CharField(label="Логин")
    password = forms.CharField(label="Пароль", widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._init_bootstrap()
        self.fields["username"].widget.attrs["autofocus"] = True
