from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.core.exceptions import ValidationError
from django.forms.widgets import FileInput
from registration.forms import RegistrationForm
from django.utils.translation import gettext as _


from apps.carers.models import Profile, Qualification, WorkExperience, Review, UserActivationCode


class MyRegForm(RegistrationForm):
    username = forms.CharField(max_length=254, required=False, widget=forms.HiddenInput())

    def clean_email(self):
        email = self.cleaned_data['email']
        self.cleaned_data['username'] = email
        return email


class SetUpFlowOneForm(forms.ModelForm):
    first_name = forms.CharField(label='Your First Name', required=True)
    middle_names = forms.CharField(label='Middle Name(s)', required=False)
    last_name = forms.CharField(label='Your Last Name', required=True)
    employer_name = forms.CharField(label='Where do you work (Care home name or Company name)?', required=False)
    employer_email = forms.EmailField(
        label='Would you like to automatically notify your employer when you get a compliment? \nEnter their email if yes.', required=False)

    class Meta:
        model = Profile
        fields = ['first_name', 'middle_names', 'last_name', 'preferred_name', 'employer_name', 'employer_email', 'avatar', 'enabled_privacy_mode',]
        widgets = {
            'avatar': FileInput(attrs={'accept': 'image/*'})
        }


class QualificationForm(forms.ModelForm):
    class Meta:
        model = Qualification
        fields = ["name"]

        labels = {
            'name': 'Qualification Name',
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

    def save(self, commit=True):
        qualification = super().save(commit=False)
        qualification.user = self.user
        if commit:
            qualification.save()
        return qualification


QualificationFormSet = forms.modelformset_factory(
    Qualification,
    form=QualificationForm,
    fields=("name",),
    extra=1
)


class WorkExperienceForm(forms.ModelForm):
    class Meta:
        model = WorkExperience
        fields = ["name"]

        labels = {
            'name': 'Where did you work / what did you do?',
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

    def save(self, commit=True):
        experience = super().save(commit=False)
        experience.user = self.user
        if commit:
            experience.save()
        return experience


WorkExperienceFormSet = forms.modelformset_factory(
    WorkExperience,
    form=WorkExperienceForm,
    fields=("name",),
    extra=1
)


class HobbiesForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['hobbies']
        labels = {
            'hobbies': 'Your hobbies'
        }


class ExtraInfoForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['extra_text']
        labels = {
            'extra_text': 'About You'
        }


class AvatarForm(forms.ModelForm):
    # Explicitly define the field here to set initial value and widget
    has_completed_setup = forms.BooleanField(
        initial=True,
        widget=forms.HiddenInput(),
        required=False  # If this field is not required by the model, set required to False
    )

    class Meta:
        model = Profile
        fields = ['avatar', 'has_completed_setup']  # Include the new field in the fields list
        labels = {
            'avatar': 'Upload an image',
        }
        widgets = {
            # This is another way to hide the field if you prefer to include it via the Meta class
            'has_completed_setup': forms.HiddenInput(),
        }

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.has_completed_setup = True  # Set the value to True regardless of form input
        if commit:
            instance.save()
        return instance


class CarerSearchForm(forms.Form):
    search = forms.CharField(required=True)


class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        fields = ['rating', 'text', 'reviewer_name', 'reviewer_first_name', 'reviewer_last_name', 'reviewer_phone', 'reviewer_email', 'relationship_to_user', 'display_initials_only']
        widgets = {
            'rating': forms.HiddenInput(),
            'text': forms.Textarea(attrs={'rows': 4}),  # Set 4 rows for the textarea
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Make the field required
        self.fields['reviewer_first_name'].required = True
        self.fields['reviewer_last_name'].required = True


class FileUploadForm(forms.Form):
    file = forms.FileField()



class ActivationPasswordForm(forms.Form):
    """
    A form that lets a user set their password and activate the account.
    """
    uuid = forms.UUIDField(widget=forms.HiddenInput())


    error_messages = {
        "password_mismatch": _("The two password fields didn’t match."),
    }
    new_password1 = forms.CharField(
        label=_("New password"),
        widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
        strip=False,
        help_text=password_validation.password_validators_help_text_html(),
    )
    new_password2 = forms.CharField(
        label=_("New password confirmation"),
        strip=False,
        widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
    )

    def clean_new_password2(self):
        password1 = self.cleaned_data.get("new_password1")
        password2 = self.cleaned_data.get("new_password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError(
                self.error_messages["password_mismatch"],
                code="password_mismatch",
            )
        password_validation.validate_password(password2)
        return password2

    def clean_uuid(self):
        data = self.cleaned_data['uuid']
        if UserActivationCode.objects.filter(uuid=data).exists():
            return data
        else:
            raise ValidationError('Invalid UUID')

