from django.views.generic import TemplateView
from django.conf import settings
from _keenthemes.__init__ import KTLayout
from _keenthemes.libs.theme import KTTheme
from authentication.models import User
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.tokens import PasswordResetTokenGenerator

from django.contrib.auth.tokens import default_token_generator
from authentication.models import User
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.decorators import user_passes_test
from django.utils.http import urlsafe_base64_decode
from django.utils.encoding import force_bytes
from django.contrib import messages
"""
This file is a view controller for multiple pages as a module.
Here you can override the page view layout.
Refer to urls.py file for more pages.
"""

class AuthNewPasswordView(TemplateView):
    template_name = 'pages/auth/new-password.html'
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)

        # A function to init the global layout. It is defined in _keenthemes/__init__.py file
        context = KTLayout.init(context)

        KTTheme.addJavascriptFile('js/custom/authentication/reset-password/new-password.js')

        # Define the layout for this module
        # _templates/layout/auth.html
        context.update({
            'layout': KTTheme.setLayout('auth.html', context),
        })

        return context
    
    def post(self, request, encoded_pk, token):
        try:
            form = request.POST 
            password=form['password']
            confirm_password=form['confirm_password']
            terms_accepted = request.POST.get('terms_accepted')
            # token = self.context.get("kwargs").get("token")
            # encoded_pk = self.context.get("kwargs").get("encoded_pk")

            # if token is None or encoded_pk is None:
            #     messages.error(request,"Missing data.")

            if not password and not confirm_password:
                messages.error(request, 'Please enter both password and repeat password.')
                return redirect('namespace-name:new-password',encoded_pk=encoded_pk, token=token)
            
            if not password:
                messages.error(request, 'Please enter a password.')
                return redirect('namespace-name:new-password', encoded_pk=encoded_pk, token=token)

            if not confirm_password:
                messages.error(request, 'Please confirm your password.')
                return redirect('namespace-name:new-password', encoded_pk=encoded_pk, token=token)

            if password != confirm_password:
                messages.error(request, 'Password and Repeat Password do not match.')
                return redirect('namespace-name:new-password', encoded_pk=encoded_pk, token=token)
            
            # if not terms_accepted:
            #     messages.error(request, 'Please accept the terms and conditions.')
            #     return redirect('namespace-name:new-password', encoded_pk=encoded_pk, token=token)
        
            pk = urlsafe_base64_decode(encoded_pk).decode()
            user = User.objects.get(id=pk) 
            
            if not PasswordResetTokenGenerator().check_token(user, token):
                messages.error(request,"The reset token is invalid")
     
            if user:
                user.set_password(password)
                user.save()
                messages.success(request, 'Your password has been reset successfully.')
                return redirect('/')
            else:
                messages.error(request, 'The password reset link is invalid or has expired.')
        except User.DoesNotExist:
            messages.error(request, 'User not found.')
            return redirect('/reset-password')
            

        
