from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
from instructor.models import Instructor

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    phone = forms.CharField(max_length=15, required=True)
    address = forms.CharField(widget=forms.Textarea, required=True)
    birth_date = forms.DateField(required=True, widget=forms.DateInput(attrs={'type': 'date'}))
    specialization = forms.CharField(max_length=100, required=True)
    experience_years = forms.IntegerField(min_value=0, required=True)

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

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        
        if commit:
            user.save()
            
            # Создаем профиль
            profile = user.profile
            profile.user_type = 'instructor'
            profile.phone = self.cleaned_data['phone']
            profile.address = self.cleaned_data['address']
            profile.birth_date = self.cleaned_data['birth_date']
            profile.save()
            
            # Создаем инструктора
            instructor = Instructor.objects.create(
                profile=profile,
                specialization=self.cleaned_data['specialization'],
                experience_years=self.cleaned_data['experience_years']
            )
            
        return user

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['phone', 'address', 'birth_date']
        widgets = {
            'birth_date': forms.DateInput(attrs={'type': 'date'}),
        } 