from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
import json, uuid
from django.core.exceptions import ValidationError
import re




class RegistrationForm(UserCreationForm):
    password1 = forms.CharField(
        widget=forms.PasswordInput,
        label='Password',
        help_text='Use minimum of 8 mixed chracters [e.g. Atuns7890]'
    )

    password2 = forms.CharField(
        widget=forms.PasswordInput,
        help_text='Re-enter password',
        label='Confirm Password'
    )

    phoneNumber = forms.CharField(
        label='Phone',
        max_length=11,
        min_length=11,
        required=True
    )

    class Meta(UserCreationForm.Meta):
        model = AppUser
        fields = (
            'firstName',
            'lastName',
            'username',
            'email',
            'phoneNumber',
            'password1',
            'password2'
        )

        help_texts = {
            'username': None,
            'email': 'Please Use Valid Email',
        }

    def clean(self):
        cleaned_data = super(RegistrationForm, self).clean()

        if 'email' in cleaned_data:
            if AppUser.objects.filter(
                email__iexact=cleaned_data['email']
            ).exists():
                raise ValidationError(
                    "This email has been taken"
                )

        if 'username' in cleaned_data:
            if AppUser.objects.filter(
                username__iexact=cleaned_data['username']
            ).exists():
                raise ValidationError(
                    "This username has been taken"
                )

        if 'phoneNumber' in cleaned_data:
            if AppUser.objects.filter(
                phoneNumber=cleaned_data['phoneNumber']
            ).exists():
                raise ValidationError(
                    "This phone number has been taken"
                )

        if 'email' in cleaned_data:
            if not cleaned_data['email'].lower().endswith(
                ("@gmail.com", "@yahoo.com")
            ):
                raise ValidationError(
                    "Please use a valid Gmail or Yahoo email"
                )

        return cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)

        user.email = self.cleaned_data['email']
        user.firstName = self.cleaned_data['firstName']
        user.lastName = self.cleaned_data['lastName']
        user.phoneNumber = self.cleaned_data['phoneNumber']
        user.category = "EARNER"

        if commit:
            user.save()

        return user

class PasswordChangeForm(UserChangeForm):
    password1 = forms.CharField(widget=forms.PasswordInput, label='Password',
                                help_text='use minimum of 8 mix characters [e.g abcd1234] ')
    password2 = forms.CharField(widget=forms.PasswordInput, help_text='Re-enter password', label='Confirm Password')


    class Meta(UserChangeForm.Meta):
        model = AppUser
        fields = ('password1', "password2")





# forms.py



from datetime import date

from django import forms


class KycForm(forms.Form):

    firstName = forms.CharField(
        label="First name",
        max_length=100
    )

    middleName = forms.CharField(
        label="Middle name",
        max_length=100,
        required=False
    )

    lastName = forms.CharField(
        label="Last name (Surname)",
        max_length=100
    )

    phone = forms.CharField(
        label="Phone number",
        max_length=20,
        widget=forms.TextInput(attrs={
            "inputmode": "tel",
            "autocomplete": "tel",
            "placeholder": "08012345678"
        })
    )

    bvn = forms.CharField(
        label="BVN",
        min_length=11,
        max_length=11,
        widget=forms.TextInput(attrs={
            "inputmode": "numeric",
            "autocomplete": "off",
            "maxlength": "11"
        })
    )

    dob = forms.DateField(
        label="Date of birth",
        widget=forms.DateInput(attrs={
            "type": "date",
            "class": "form-control"
        })
    )

    def clean_firstName(self):
        value = self.cleaned_data["firstName"].strip()

        if not value:
            raise forms.ValidationError("Enter your first name.")

        return value

    def clean_middleName(self):
        return self.cleaned_data.get("middleName", "").strip()

    def clean_lastName(self):
        value = self.cleaned_data["lastName"].strip()

        if not value:
            raise forms.ValidationError("Enter your last name.")

        return value

    def clean_bvn(self):
        value = self.cleaned_data["bvn"].strip()

        if not value.isdigit() or len(value) != 11:
            raise forms.ValidationError(
                "BVN must contain exactly 11 digits."
            )

        return value

    def clean_phone(self):
        value = self.cleaned_data["phone"].strip()

        value = re.sub(r"[\s\-()]", "", value)

        if value.startswith("+234"):
            value = "0" + value[4:]
        elif value.startswith("234"):
            value = "0" + value[3:]

        if not value.isdigit() or len(value) != 11 or not value.startswith("0"):
            raise forms.ValidationError(
                "Enter a valid Nigerian phone number."
            )

        return value

    def clean_dob(self):
        value = self.cleaned_data["dob"]

        if value >= date.today():
            raise forms.ValidationError(
                "Date of birth must be in the past."
            )

        return value



import re
from django import forms
from django.core.exceptions import ValidationError


def normalize_nigerian_phone(value):
    phone = re.sub(r'\D', '', str(value))

    if phone.startswith('234') and len(phone) == 13:
        phone = '0' + phone[3:]

    if len(phone) != 11 or not phone.startswith('0'):
        raise ValidationError(
            'Enter a valid Nigerian phone number.'
        )

    return phone


class DataForm(forms.Form):
    network = forms.ChoiceField(
        widget=forms.Select,
        choices=(
            ('---', '-------'),
            ('MTN', 'MTN'),
            ('GLO', 'GLO'),
            ('AIRTEL', 'AIRTEL'),
            ('9MOBILE', '9MOBILE')
        )
    )

    type = forms.ChoiceField(
        widget=forms.Select,
        choices=(('---', '-------'), ('---', '-------'))
    )

    plan = forms.ChoiceField(
        widget=forms.Select,
        choices=(('---', '-------'), ('---', '-------'))
    )

    phone = forms.CharField(max_length=25, required=True)

    valid = forms.BooleanField(
        label='Bypass validator',
        required=False
    )

    def clean_phone(self):
        return normalize_nigerian_phone(
            self.cleaned_data.get('phone', '')
        )



class AirtimeForm(forms.Form):
    network = forms.ChoiceField(
        widget=forms.Select,
        choices=(
            ('---', '-------'),
            ('---', '-------'),
        )
    )

    phone = forms.CharField(
        max_length=25,
        required=True,
        widget=forms.TextInput(attrs={
            'type': 'tel',
            'inputmode': 'numeric',
            'autocomplete': 'tel',
        })
    )

    amount = forms.IntegerField(min_value=0)

    valid = forms.BooleanField(
        label='Bypass validator',
        required=False
    )

    def clean_phone(self):
        return normalize_nigerian_phone(
            self.cleaned_data['phone']
        )


    
class RechargeForm(forms.Form):
    network = forms.ChoiceField(widget=forms.Select, choices=(('---', '-------'), ('---', '-------')))
    quantity = forms.IntegerField(min_value=0,)
    amount = forms.ChoiceField(widget=forms.Select, choices=(('---', '----'), (100, '₦100'), (200, '₦200'), (500, '₦500'), (1000, '₦1000')))
    

class ElectricForm(forms.Form):
    service = forms.CharField(widget=forms.Select(choices=[('---', '----'), ('---', '----')]))
    amount = forms.IntegerField(min_value=0,)
    meter_num = forms.CharField(label='Meter number')


class TvForm(forms.Form):
    service = forms.ChoiceField(widget=forms.Select, choices=(('---', '-------'), ('dstv', 'DStv'), ('gotv', 'GOtv'), ('startimes', 'STARTIMES')))
    plan = forms.CharField(widget=forms.Select(choices=[('---', '----'), ('---', '----')]))
    iuc = forms.CharField(label='IUC number')


class ConvertAirtimeForm(forms.Form):
    network = forms.ChoiceField(widget=forms.Select, choices=(('MTN', 'MTN'), ('GLO', 'GLO'), ('AIRTEL', 'AIRTEL'), ('9MOBILE', '9MOBILE')))
    amount = forms.IntegerField(min_value=0,)
    phone = forms.CharField(max_length = 11, min_length = 11)


class ResultForm(forms.Form):
    exam_type = forms.ChoiceField(widget=forms.Select, choices=(('---', '----'), ('---', '----')))
    quantity = forms.IntegerField(min_value=0, help_text='e.g 1')
    phone = forms.CharField(max_length = 11, min_length = 11)


class QueryForm(forms.Form):
    query = forms.CharField(help_text='Enter status or phone number')
    
class WalletForm(forms.Form):
    query = forms.CharField(help_text='Filter with Phone No., Meter No., Smart card No., or any related text in your transaction, e.g Monnify, Pin etc')


class FindForm(forms.Form):
    user = forms.CharField(help_text='Enter user email')

class UpgradeForm(forms.Form):
    email = forms.CharField(help_text='Enter user email')
    level = forms.ChoiceField(widget=forms.Select, choices=(('EARNER', 'EARNER'), ('AFFILIATE', 'AFFILIATE'), ('AMBASSADOR', 'AMBASSADOR'), ('API1', 'API1'), ('API2', 'API2'), ('API3', 'API3')))




class UpgradeFormUser(forms.Form):
    level = forms.ChoiceField(widget=forms.Select,label=' ',required=False, choices=(('---', '---'),('AFFILIATE', 'Affiliate'), ('AMBASSADOR', 'Ambassador')))
    


class DateForm(forms.Form):
    date = forms.DateField(widget=forms.DateInput(
                attrs={'type': 'date', 'placeholder': 'yyyy-mm-dd (DOB)', 'class': 'form-control'}
            ))

class ManualFundForm(forms.Form):
    amount = forms.IntegerField(min_value=0,)

class ForgotForm(forms.Form):
    email = forms.CharField(help_text='Enter email')


class BulkForm(forms.Form):
    sender = forms.CharField(label='From[Sender name]')
    phoneNumbers = forms.CharField(widget=forms.Textarea, label='To[Recipients]', help_text='Enter or paste phone numbers separated with comma. No spaces,[ e.g 09000000000,08189999999,07011111111]')
    message = forms.CharField(label='Message')

class BucketForm(forms.Form):
    network = forms.ChoiceField(widget=forms.Select, choices=(('---', '-------'), ('mtn_sme', 'MTN SME'), ('mtn_cg', 'MTN CG'), ('glo_cg', 'GLO CG'), ('airtel_cg', 'AIRTEL CG'), ('mobile_cg', '9MOBILE CG')))
    plan = forms.CharField(widget=forms.Select(choices=[('---', '----'), ('---', '----')]))


class NotifyForm(forms.Form):
    users = forms.CharField(label='Enter All for all users or enter the index you wish to notify, e.g 1 to 50 or Username')
    message = forms.CharField(widget=forms.Textarea, label='Message', help_text='Enter message')



class PinForm(forms.Form):
    pin = forms.CharField(widget=forms.PasswordInput, max_length = 5, min_length = 5)
    confirm_pin = forms.CharField(widget=forms.PasswordInput, max_length = 5, min_length = 5)
    
    def clean(self):
        cleaned_data = super(PinForm, self).clean()
        pin1 = cleaned_data['pin']
        pin2 = cleaned_data['confirm_pin']
        
        if pin1 != pin2:
            raise ValidationError("Pin Does Not Match!")
        elif pin1.isdigit() is not True:
            raise ValidationError("Only Numbers Allowed!")






class ChangePinForm(forms.Form):

    old_pin = forms.CharField(
        widget=forms.PasswordInput,
        max_length=5,
        min_length=5,
        required=True
    )

    new_pin = forms.CharField(
        widget=forms.PasswordInput,
        max_length=5,
        min_length=5,
        required=True
    )

    confirm_pin = forms.CharField(
        widget=forms.PasswordInput,
        max_length=5,
        min_length=5,
        required=True
    )

    def clean(self):

        cleaned_data = super().clean()

        pin1 = cleaned_data.get("new_pin")
        pin2 = cleaned_data.get("confirm_pin")

        if pin1 and pin2:

            if pin1 != pin2:

                raise ValidationError(
                    "The new transaction PINs do not match."
                )

            if not pin1.isdigit():

                raise ValidationError(
                    "Transaction PIN must contain numbers only."
                )

        return cleaned_data


class ResetPinForm(forms.Form):

    password = forms.CharField(
        widget=forms.PasswordInput,
        required=True
    )

    pin = forms.CharField(
        widget=forms.PasswordInput,
        max_length=5,
        min_length=5,
        required=True
    )

    confirm_new_pin = forms.CharField(
        widget=forms.PasswordInput,
        max_length=5,
        min_length=5,
        required=True
    )

    def clean(self):

        cleaned_data = super().clean()

        pin1 = cleaned_data.get("pin")
        pin2 = cleaned_data.get("confirm_new_pin")

        if pin1 and pin2:

            if pin1 != pin2:

                raise ValidationError(
                    "The new transaction PINs do not match."
                )

            if not pin1.isdigit():

                raise ValidationError(
                    "Transaction PIN must contain numbers only."
                )

        return cleaned_data

class IpayForm(forms.Form):
    sessionID = forms.CharField(help_text='Enter the Session ID on the payment reciept.')
    amount = forms.IntegerField(min_value=0,)


class DateFormAdmin(forms.Form):
    date = forms.DateField(widget=forms.DateInput(
                attrs={'type': 'date', 'placeholder': 'yyyy-mm-dd (DOB)', 'class': 'form-control'}
            ))
    username = forms.CharField(help_text='Enter username or "all" for all users ')


