# forms.py
from django import forms
from django.contrib.auth.forms import AuthenticationForm

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

from .models import UserProfile

class CustomLoginForm(AuthenticationForm):
    username = forms.CharField(widget=forms.TextInput(attrs={
        'placeholder': 'Username'
    }))
    password = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Password'
    }))

# forms.py

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update({
            'placeholder': 'Username'
        })
        self.fields['email'].widget.attrs.update({
            'placeholder': 'Email'
        })
        self.fields['password1'].widget.attrs.update({
            'placeholder': 'Password'
        })
        self.fields['password2'].widget.attrs.update({
            'placeholder': 'Confirm Password'
        })


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['profile_picture', 'position', 'signed_picture']  # Include the fields you want to manage

class UserCustomForm(forms.ModelForm):
    # Profile fields
    profile_picture = forms.ImageField(required=False, label="Profile Picture")
    signed_picture = forms.ImageField(required=False, label="Signed Picture")
    position = forms.ChoiceField(
        choices=UserProfile.POSITION_CHOICES,
        required=False,
        label="Position"
    )
    qa2_default = forms.BooleanField(required=False, label="QA.2 Default")

    class Meta:
        model = User
        fields = [
            "first_name",
            "last_name",
            "is_staff",
            "is_superuser",
            "is_active",
        ]

    def __init__(self, *args, **kwargs):
        # Allow passing `instance` to access both User and UserProfile objects
        user_instance = kwargs.pop('instance', None)
        profile_instance = getattr(user_instance, 'profile', None)
        super().__init__(instance=user_instance, *args, **kwargs)

        # Populate initial data for profile fields if `profile` exists
        if profile_instance:
            self.fields['profile_picture'].initial = profile_instance.profile_picture
            self.fields['signed_picture'].initial = profile_instance.signed_picture
            self.fields['position'].initial = profile_instance.position
            self.fields['qa2_default'].initial = profile_instance.qa2_default

    def save(self, commit=True):
        # Save the User instance first
        user = super().save(commit=commit)
        profile_data = {
            'profile_picture': self.cleaned_data.get('profile_picture'),
            'signed_picture': self.cleaned_data.get('signed_picture'),
            'position': self.cleaned_data.get('position'),
            'qa2_default': self.cleaned_data.get('qa2_default'),
        }

        # Ensure profile exists for the user
        profile, created = UserProfile.objects.get_or_create(user=user)
        for key, value in profile_data.items():
            setattr(profile, key, value)
        if commit:
            profile.save()

        return user
