from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import gettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, HTML, Layout, Fieldset, Submit, Field
from crispy_forms.bootstrap import FormActions, Tab, TabHolder

from .models import User


class LoginForm(AuthenticationForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'autofocus': True}))
    class Meta:
        model = User
        fields = ('email', 'password')

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields.pop('username', None)

    def clean(self):
        cleaned_data = super(LoginForm, self).clean()
        if 'username' in cleaned_data:
            del cleaned_data['username']
        return cleaned_data

    def get_user(self):
        try:
            user = User.objects.get(email=self.cleaned_data.get('email'))

            # check if the user is active
            if not user.is_active:
                raise forms.ValidationError("User is not active")
            # check password
            if not user.check_password(self.cleaned_data.get('password')):
                raise forms.ValidationError("Invalid password")

            return user
        except User.DoesNotExist:
            return None


class UserRegistrationForm(forms.ModelForm):
    password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_('Password confirmation'), widget=forms.PasswordInput)

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

    def __init__(self, *args, **kwargs):
        super(UserRegistrationForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary d-block mx-auto'))
        self.fields['first_name'].required = True
        self.fields['last_name'].required = True

        self.helper.layout = Layout(
            Fieldset(
                '',
                Div(
                    Div('first_name', css_class="col-6"),
                    Div('last_name', css_class="col-6"),
                    css_class="row"
                ),
                Div(
                    Div('email', 'password1', 'password2',
                        css_class="col-12"),
                    css_class="row"
                ),

            ),
        )


class ChangePasswordForm(forms.Form):
    password = forms.CharField(label=_('Old password'), widget=forms.PasswordInput)
    password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_('Password confirmation'), widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary d-block mx-auto'))

        self.fields['password'].required = True
        self.fields['password1'].required = True
        self.fields['password2'].required = True

        self.helper.layout = Layout(
            Fieldset(
                '',
                Div(
                    Div('password', 'password1', 'password2',
                        css_class="col-12"),
                    css_class="row"
                ),

            ),
        )


class ResetPasswordForm(forms.Form):
    email = forms.CharField(widget=forms.HiddenInput())
    reset_code = forms.CharField(widget=forms.HiddenInput())
    password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_('Password confirmation'), widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        super(ResetPasswordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary d-block mx-auto'))

        self.fields['email'].required = True
        self.fields['reset_code'].required = True
        self.fields['password1'].required = True
        self.fields['password2'].required = True

        self.helper.layout = Layout(
            Fieldset(
                '',
                Div(
                    Div('email', 'reset_code', 'password1', 'password2',
                        css_class="col-12"),
                    css_class="row"
                ),

            ),
        )

class ForgotPasswordForm(forms.Form):
    email = forms.EmailField(label=_('Email'), widget=forms.EmailInput)

    def __init__(self, *args, **kwargs):
        super(ForgotPasswordForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary d-block mx-auto'))

        self.fields['email'].required = True

        self.helper.layout = Layout(
            Fieldset(
                '',
                Div(
                    Div('email', css_class="col-12"),
                    css_class="row"
                ),

            ),
        )

    def get_user(self):
        try:
            user = User.objects.get(
                email=self.cleaned_data.get('email'),
                is_active=True
            )
            return user
        except User.DoesNotExist:
            return None
