from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm

from .models import User
from .phone import normalize_phone


class PhoneForm(forms.Form):
    phone = forms.CharField(max_length=16, label='شماره موبایل')
    name = forms.CharField(max_length=100, required=False, label='نام و نام خانوادگی')
    email = forms.EmailField(required=False, label='ایمیل')

    def clean_phone(self):
        return normalize_phone(self.cleaned_data['phone'])


class OTPForm(forms.Form):
    code = forms.RegexField(r'^\d{6}$', label='کد یک‌بارمصرف', error_messages={'invalid': 'کد باید دقیقاً ۶ رقم باشد.'})


class AdminUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = User
        fields = ('phone', 'name', 'email')

    def clean_phone(self):
        return normalize_phone(self.cleaned_data['phone'])


class AdminUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = User
        fields = '__all__'

    def clean_phone(self):
        return normalize_phone(self.cleaned_data['phone'])
