# from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from turnstile.fields import TurnstileField

from .models import CallbackRequest, Profile


User = get_user_model()

class CallbackForm(forms.ModelForm):
    # captcha = CaptchaField(label='Введите текст с картинки', required=True)
    captcha = TurnstileField(label='', theme='light', size='normal')   
     
    class Meta:
        model = CallbackRequest
        fields = ['name', 'phone', 'email', 'question']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-input',
                'placeholder': 'Ваше имя'
            }),
            'phone': forms.TextInput(attrs={
                'class': 'form-input',
                'placeholder': '+7 (___) ___-__-__'
            }),
            'email': forms.EmailInput(attrs={
                'class': 'form-input',
                'placeholder': 'your@email.com'
            }),
            'question': forms.Textarea(attrs={
                'class': 'form-textarea',
                'placeholder': 'Опишите ваш вопрос или задачу...',
                'rows': 4
            }),
        }
        labels = {
            'name': 'Имя',
            'phone': 'Телефон',
            'email': 'Электронная почта',
            'question': 'Ваш вопрос'
        }

        def __init__(self, *args, **kwargs):
            # Извлекаем request из kwargs, если он передан
            self.request = kwargs.pop('request', None)
            super().__init__(*args, **kwargs)

            # Если пользователь авторизован — удаляем поле капчи
            if self.request and self.request.user.is_authenticated:
                del self.fields['captcha']


class UserEditForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Имя'}),
            'last_name': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Фамилия'}),
            'email': forms.EmailInput(attrs={'class': 'form-input', 'placeholder': 'Email'}),
        }


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['phone', 'company', 'specialization', 'avatar', 'email_notifications']
        widgets = {
            'phone': forms.TextInput(attrs={'class': 'form-input', 'placeholder': '+7 (___) ___-__-__'}),
            'email_notifications': forms.CheckboxInput(attrs={'class': 'form-checkbox'}),
            'company': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Название компании'}),
            'specialization': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Специализация'}),
            'avatar': forms.FileInput(attrs={'class': 'form-file'}),
            'email_notifications': forms.CheckboxInput(attrs={'class': 'form-checkbox'}),
        }


class RegistrationForm(UserCreationForm):
    captcha = TurnstileField(label='', theme='light', size='normal')  
    # Поля пользователя
    first_name = forms.CharField(
        max_length=30,
        required=True,
        label='Имя',
        widget=forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Имя'})
    )
    last_name = forms.CharField(
        max_length=30,
        required=False,
        label='Фамилия',
        widget=forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Фамилия'})
    )
    email = forms.EmailField(
        required=True,
        widget=forms.EmailInput(attrs={'class': 'form-input', 'placeholder': 'Email'})
    )

    # Поля профиля
    phone = forms.CharField(
        max_length=20,
        required=False,
        label='Телефон',
        widget=forms.TextInput(attrs={'class': 'form-input', 'placeholder': '+7 (___) ___-__-__'})
    )
    company = forms.CharField(
        max_length=255,
        required=False,
        label='Компания',
        widget=forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Компания'})
    )
    specialization = forms.CharField(
        max_length=100,
        required=False,
        label='Специализация',
        widget=forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Специализация'})
    )

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

    def save(self, commit=True):
        user = super().save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
            # Создаём или обновляем профиль
            profile, created = Profile.objects.get_or_create(user=user)
            profile.phone = self.cleaned_data['phone']
            profile.company = self.cleaned_data['company']
            profile.specialization = self.cleaned_data['specialization']
            profile.save()
        return user