from ckeditor.fields import RichTextField
from ckeditor_uploader.widgets import CKEditorUploadingWidget
from django import forms
from django.contrib.auth import get_user_model
from django.db.models import Q

from posts.models import Post

User = get_user_model()


class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput())
    password2 = forms.CharField(
        label="Confirm Password", widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ["first_name", "last_name", "username", "email"]

    def clean_password(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords Don't Match")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])

        if commit:
            user.save()
        return user


class RegisterForm(UserCreationForm):
    def __init__(self, data=None, *args, **kwargs):
        super().__init__(data=data, *args, **kwargs)

        self.fields['first_name'].widget.attrs['placeholder'] = 'First Name'
        self.fields['last_name'].widget.attrs['placeholder'] = 'Last Name'
        self.fields['email'].widget.attrs['placeholder'] = 'Email'
        self.fields['username'].widget.attrs['placeholder'] = 'Username'
        self.fields['password1'].widget.attrs['placeholder'] = 'Password'
        self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password'

        for field in self.fields.values():
            field.widget.attrs["onblur"] = "this.placeholder = '{}'".format(
                field.widget.attrs["placeholder"])
            field.widget.attrs['class'] = 'single-input'
            field.widget.attrs["onfocus"] = "this.placeholder = ''"
            field.required = True
            field.label = ""


class UserLoginForm(forms.Form):
    query = forms.CharField(label="", widget=forms.TextInput())
    password = forms.CharField(label="", widget=forms.PasswordInput())

    def clean(self, *args, **kwargs):
        query = self.cleaned_data.get("query")
        password = self.cleaned_data.get("password")
        user_qs_final = User.objects.filter(
            Q(username__iexact=query) |
            Q(email__iexact=query)
        ).distinct()
        if not user_qs_final.exists() and user_qs_final.count != 1:
            raise forms.ValidationError("Invalid Credentials")

        user_obj: User = user_qs_final.first()

        if not user_obj.check_password(password):
            raise forms.ValidationError("Invalid Credentials")

        self.cleaned_data["user_obj"] = user_obj
        return super(UserLoginForm, self).clean(*args, **kwargs)


class LoginForm(UserLoginForm):
    def __init__(self, data=None, *args, **kwargs):
        super().__init__(data=data, *args, **kwargs)

        self.fields['query'].widget.attrs['placeholder'] = 'Username or Email'
        self.fields['password'].widget.attrs['placeholder'] = 'Password'

        for field in self.fields.values():
            field.widget.attrs["onblur"] = "this.placeholder = '{}'".format(
                field.widget.attrs["placeholder"])
            field.widget.attrs['class'] = 'single-input'
            field.widget.attrs["onfocus"] = "this.placeholder = ''"
            field.required = True
            field.label = ""
