from django.shortcuts import render
from rest_framework import status
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import check_password, make_password
import json
import random
from django.template.loader import render_to_string 
from django.utils.html import strip_tags 
from django.core.mail import send_mail, EmailMultiAlternatives
from django.db.models import Q
from authentication.models import User
from authentication.serializer import ProfileSerializer
from .auth import generate_access_token, verify_token


@csrf_exempt
def login(request):
    if request.method == 'POST':
        request_data = json.loads(request.body)
        try:
            user = User.objects.get(email=request_data['email'])
            if check_password(request_data['password'], user.password):
                token = generate_access_token(user)
                return JsonResponse({'message' : "Login successfully.", 'token' : token, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
            else:
                return JsonResponse({'message' : "Invalid password.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            return JsonResponse({'message' : "Invalid email id.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({'message' : "Invalid HTTP request.", 'status':status.HTTP_405_METHOD_NOT_ALLOWED}, safe=False, status=status.HTTP_400_BAD_REQUEST)


@csrf_exempt
def changePassword(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message':"User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        if request.method == 'POST' :
            request_data = json.loads(request.body)
            user = User.objects.get(id=user_id)
            user.password = make_password(request_data['password'])
            user.save()
            return JsonResponse({'message' : "Password Updated successfully.", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            return JsonResponse({'message' : "Invalid HTTP request.", 'status':status.HTTP_405_METHOD_NOT_ALLOWED}, safe=False, status=status.HTTP_400_BAD_REQUEST)

@csrf_exempt
def requestOtp(request):
    try:
        request_data = json.loads(request.body)
        user = User.objects.get(email = request_data['email'])
        otp = ''.join((random.choice('1234567890') for i in range(4)))
        request.session['otp'] = otp
        request.session['user_id'] = user.id
        subject = "DRIVERZZ OTP request"
        to_email = [user.email]
        html_template = render_to_string("authentication/otp-template.html", {'logo' : settings.LOGO_URL, 'name' : user.name,  'otp' : otp}) 
        text_content = strip_tags(html_template)  
        email = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, to_email)
        email.attach_alternative(html_template, "text/html")
        email.send()
        return JsonResponse({'message' : "OTP sent to registered Email", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        return JsonResponse({'message' : "OTP unable to sent.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        return JsonResponse({'message' : "Something went wrong. Please try again later.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)

@csrf_exempt
def verifyOtp(request):
        request_data = json.loads(request.body)     
        otp = request_data['otp']
        if(otp == request.session['otp']):
            return JsonResponse({'message' : "OTP Matched", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            return JsonResponse({'message' : "OTP Not Matched", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)

@csrf_exempt
def changeForgotPassword(request):
    try:
        request_data = json.loads(request.body)
        password = request_data['password']
        user = User.objects.get(id = request.session['user_id'])
        user.set_password(password)
        user.save()
        return JsonResponse({'message':"password changed successfully", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        return JsonResponse({'message':"User does't exist", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(e)
        return JsonResponse({'message':"Something went wrong. Please try again later.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    


@csrf_exempt
def profile(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        if request.method == 'POST':
            user = User.objects.get(id=user_id)
            user.name = request.POST.get('name')
            user.email = request.POST.get('email')
            user.mobile = request.POST.get('mobile')
            if request.FILES:
                user.profile_pic = request.FILES['profile_pic']
            user.save()
            return JsonResponse({'message' : "Profile added successfully.", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            user = User.objects.get(id=user_id)
            serializer = ProfileSerializer(user, many=False)
            return JsonResponse({'user' : serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        


@csrf_exempt
def Customers(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        if request.method == 'GET':
            customers = User.objects.filter(user_type = 2)
            serializer = ProfileSerializer(customers, many=True)
            return JsonResponse({'customers' : serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            request_data = json.loads(request.body)
            try:
                user = User.objects.get(
                    Q(mobile=request_data['mobile'], user_type=2) | 
                    Q(email=request_data['email'], user_type=2)
                )
                return JsonResponse({'message' : "Email ID or mobile no already exist.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
            except User.DoesNotExist:
                user = User()
                user.mobile = request_data['mobile']
                user.name = request_data['name']
                user.email = request_data['email']
                user.is_active = 1
                user.is_staff = 0
                user.is_superuser = 0
                username = ''.join((random.choice('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(6)))
                user.username = 'USER-' + username
                user.user_type = 2
                user.save()
                return JsonResponse({'message' : "Customer created successfully.", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)



@csrf_exempt
def Customer(request, id):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        if request.method == 'GET':
            pass
            # customers = User.objects.filter(user_type = 2)
            # serializer = ProfileSerializer(customers, many=True)
            # return JsonResponse({'customers' : serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            request_data = json.loads(request.body)
            try:
                users = User.objects.filter(
                    (Q(mobile=request_data['mobile'], user_type=2) | 
                     Q(email=request_data['email'], user_type=2))
                )
                user = users.first() if users.exists() else None
                if user is None:
                    raise User.DoesNotExist
                
                print(user.id)
                print(id)

                if user.id == id:
                    user = User.objects.get(id = id)
                    user.mobile = request_data['mobile']
                    user.name = request_data['name']
                    user.email = request_data['email']
                    user.save()
                    return JsonResponse({'message' : "Customer updated successfully.", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
                else:
                    return JsonResponse({'message' : "Email ID or mobile no already exist.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
            except User.DoesNotExist:
                user = User.objects.get(id = id)
                user.mobile = request_data['mobile']
                user.name = request_data['name']
                user.email = request_data['email']
                user.save()
                return JsonResponse({'message' : "Customer updated successfully.", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)