from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login as auth_login, logout
from .models import CustomUser, JobPosting
from skyonnadmin.models import ClientDetails,SubcompanyDetails,Locations,AddContact,InternalTeam
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Q

from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
import os
from django.core.files.storage import FileSystemStorage
import json
from django.core.serializers.json import DjangoJSONEncoder

def home(request):
    return render(request, 'user/home.html')


def create_user(request):
    if request.method == 'POST':
        # Handle signup form submission
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        phone = request.POST.get('phone')
        phone2 = request.POST.get('phone_2')
        company_email = request.POST.get('company_email')
        personal_email = request.POST.get('personal_email')
        address = request.POST.get('address')
        work_location = request.POST.get('work_location')
        role = request.POST.get('role')
        password = request.POST.get('password')
        picture = request.FILES.get('picture')

        # Create user_id based on role
        role_prefix = role[0].upper()
        user_count = CustomUser.objects.filter(role=role).count() + 1
        user_id = f"{role_prefix}{first_name[:3].upper()}{user_count:03}"

        # Create the CustomUser object
        user = CustomUser.objects.create(
            first_name=first_name,
            last_name=last_name,
            phone=phone,
            phone2=phone2,
            company_email=company_email,
            personal_email=personal_email,
            address=address,
            work_location=work_location,
            role=role,
            user_id=user_id
        )
        user.set_password(password)
        user.picture = picture
        user.save()
        user.backend = 'user.backend.PhoneAuthenticationBackend'
        auth_login(request, user)

        return redirect('dashboard', user_id=user.user_id)
    else:
        return render(request, 'user/home.html')


# def user_login(request):
#     if request.method == 'POST':
#         phone = request.POST.get('phone')
#         password = request.POST.get('password')
#
#         user = authenticate(request, phone=phone, password=password)
#         # print(phone, password, user)
#         if user is not None:
#             auth_login(request, user)
#             user = CustomUser.objects.filter(phone=phone).first()
#             if user:
#                 # print(user.user_id)
#                 return redirect('dashboard', user_id=user.user_id)
#             else:
#                 messages.error(request, 'No user found for the provided phone number.')
#         else:
#             messages.error(request, 'Invalid phone number or password.')
#
#     return render(request, 'user/home.html')


def user_login(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')

        if not phone and 'phone' in request.POST:
            return JsonResponse({'error': 'Please fill the phone number field.'}, status=400)
        if not password and 'password' in request.POST:  # Validate password if it's present
            return JsonResponse({'error': 'Please fill the password field.'}, status=400)

        user = InternalTeam.objects.filter(Login=phone).first()
        if user is None:
            return JsonResponse({'error': 'Incorrect Email.'}, status=404)

        if password:
            match = InternalTeam.objects.filter(Login=phone,Password=password).first()
            if not match:
                return JsonResponse({'error': 'Incorrect password.'}, status=401)

            return JsonResponse(
                {'success': 'Login successful', 'redirect_url': f'/user/dashboard/{user.user_id}'})

        return JsonResponse({'success': 'Phone number is valid.'}, status=200)

    return JsonResponse({'error': 'Invalid request method.'}, status=405)


def dashboard(request, user_id):
    # Retrieve the manager object using manager_id
    user = get_object_or_404(InternalTeam, user_id=user_id)
    print('user_id:',user_id)

    # Get the manager's first name
    first_name = user.FirstName.capitalize()
    last_name = user.LastName.capitalize()
    full_name = f"{first_name}'s"

    return render(request, 'user/dashboard.html', {'first_name': full_name, 'user_id': user_id})

# def dashboard(request, user_id):
#         # Retrieve the manager object using manager_id
#         user = get_object_or_404(CustomUser, user_id=user_id)
#         print('user_id:', user_id)
#
#         # Get the manager's first name
#         first_name = user.FirstName.capitalize()
#         full_name = f"{first_name}'s"
#         print(full_name)
#
#         if user.role == 'manager':
#            print("hiii")
#            return render(request, 'user/test.html', {'first_name': full_name, 'user_id': user_id})
#
#         if user.role == 'recruiter':
#            return render(request, 'recruiter/recruiter_dashboard.html', {'first_name': full_name, 'user_id': user_id})


def new_job_posting(request):
    locations = Locations.objects.all()
    clients = ClientDetails.objects.all()
    return render(request, 'user/new_job_posting.html', {'clients': clients,'locations':locations})


def add_recruiter(request):
    user_id = request.GET.get('user_id', None)
    print(user_id)
    context = {'user_id': user_id}
    return render(request, 'user/add_recruiter.html', context)


def logout_view(request):
    logout(request)
    return redirect('home')


# def save_job_posting(request):
#     if request.method == 'POST':
#         client = request.POST.get('Client')
#         spoc = request.POST.get('SPOC')
#         start_date = request.POST.get('StartDate')
#         budget_max = request.POST.get('BudgetMax')
#         budget_min = request.POST.get('BudgetMin')
#         job_description = request.POST.get('JobDescription')
#         special_instructions = request.POST.get('SpecialInstructions')
#         job_id = request.POST.get('JobID')
#         spoc_2 = request.POST.get('SPOC2')
#         close_date = request.POST.get('CloseDate')
#         locations = request.POST.getlist('Location')  # Use getlist to handle multiple selections
#         no_of_posting = request.POST.get('NoOfPosting')
#         job_type = request.POST.get('Type')
#         header = request.POST.get('Header')
#         experience_in_years = request.POST.get('Experience_in_Yrs')
#
#         job_posting = JobPosting(
#             client=client,
#             spoc=spoc,
#             budget_min=budget_min,
#             start_date=start_date,
#             budget_max=budget_max,
#             job_description=job_description,
#             special_instructions=special_instructions,
#             job_id=job_id,
#             spoc_2=spoc_2,
#             close_date=close_date,
#             no_of_posting=no_of_posting,
#             job_type=job_type,
#             header=header,
#             experience_in_years=experience_in_years
#         )
#         job_posting.set_locations(locations)  # Save the locations as a comma-separated string
#         job_posting.save()
#         return JsonResponse({'status': 'success', 'message': 'Job posting saved successfully.'})
#
#     return redirect('error_url')
#

def save_job_posting(request):
    if request.method == 'POST':
        # Extract data from the form
        Client = request.POST.get('Client', '')
        JobID = request.POST.get('JobID', '')
        Location = request.POST.get('Location', '')
        SPOC = request.POST.get('SPOC', '')
        SPOC2 = request.POST.get('SPOC2', '')
        StartDate = request.POST.get('StartDate', '')
        CloseDate = request.POST.get('CloseDate', '')
        BudgetMin = request.POST.get('BudgetMin', '')
        timePeriod = request.POST.get('timePeriod', '')
        minAmount = request.POST.get('minAmount', '')
        maxAmount = request.POST.get('maxAmount', '')
        Header = request.POST.get('Header', '')
        JobDescription = request.POST.get('JobDescription', '')
        Experience_in_Yrs = request.POST.get('Experience', '')
        NoOfPosting = request.POST.get('NoOfPosting', '')
        Qualification = request.POST.get('Qualification', '').upper()
        SpecialInstructions = request.POST.get('SpecialInstructions', '')

        JD = None
        slice_JD = None
        if request.FILES.get('JD'):
            myfile = request.FILES['JD']
            file_extension = os.path.splitext(myfile.name)[1]  # Get the file extension
            filename = f"{JobID}{file_extension}"  # Create the new filename using job_id
            fs = FileSystemStorage()
            filename = fs.save(filename, myfile)
            JD = fs.url(filename)  # Get the URL to the file
            slice_JD = JD[7:]

        jobposting = JobPosting(
            Client=Client,
            JobID=JobID,
            Location=Location,
            SPOC=SPOC,
            SPOC2=SPOC2,
            StartDate=StartDate,
            CloseDate=CloseDate,
            BudgetMin=BudgetMin,
            timePeriod=timePeriod,
            minAmount=minAmount,
            maxAmount=maxAmount,
            Qualification=Qualification,
            Header=Header,
            JobDescription=JobDescription,
            Experience_in_Yrs=Experience_in_Yrs,
            NoOfPosting=NoOfPosting,
            SpecialInstructions=SpecialInstructions,
            JD=JD,
            slice_JD=slice_JD
        )
        jobposting.save()
        print(jobposting)

        admin_id = request.GET.get('admin_id', None)
        print(admin_id)

        return JsonResponse({'status': 'success', 'message': 'Job_posting saved successfully.'})

    else:
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)



def create_recruiter(request):
    if request.method == 'POST':
        # Handle signup form submission
        # print(request.post)
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        phone = request.POST.get('phone')
        phone2 = request.POST.get('phone_2')
        company_email = request.POST.get('company_email')
        personal_email = request.POST.get('personal_email')
        address = request.POST.get('address')
        work_location = request.POST.get('work_location')
        role = "recruiter"  # request.POST.get('role')
        password = request.POST.get('password')
        picture = request.FILES.get('picture')
        manager_assigned = request.POST.get('manager_assigned', None)
        print(manager_assigned, 1)
        # Create user_id based on role
        role_prefix = role[0].upper()
        user_count = CustomUser.objects.filter(role=role).count() + 1
        user_id = f"{role_prefix}{first_name[:3].upper()}{user_count:03}"

        # Create the CustomUser object
        user = CustomUser.objects.create(
            first_name=first_name,
            last_name=last_name,
            phone=phone,
            phone2=phone2,
            company_email=company_email,
            personal_email=personal_email,
            address=address,
            work_location=work_location,
            role=role,
            user_id=user_id,
            manager_assigned=manager_assigned
        )
        user.set_password(password)
        user.picture = picture
        user.save()
        return redirect('dashboard', user_id=manager_assigned)
        # return JsonResponse({'success': True, 'message': 'Recruiter added successfully!'})

    else:
        messages.success(request, 'Data saved successfully.')

        # Instead of redirecting, render the same form page again
        return render(request, 'user/add_recruiter.html')


def send_message(request, recipient_id):
    recipient = get_object_or_404(User, pk=recipient_id)
    if request.method == 'POST':
        subject = request.POST.get('subject')
        body = request.POST.get('body')
        message = Message.objects.create(sender=request.user, recipient=recipient, subject=subject, body=body)
        return redirect('messages')
    return render(request, 'send_message.html', {'recipient': recipient})


def mark_as_read(request, message_id):
    message = get_object_or_404(Message, pk=message_id, recipient=request.user)
    message.is_read = True
    message.save()
    return redirect('messages')


def get_locations(request):
    if request.method == 'GET':
        client = request.GET.get('Client')
        jobposting_locations = JobPosting.objects.filter(Client=client).values_list('Location').distinct()
        client_locations = ClientDetails.objects.filter(parent_company=client).values_list('location_Id').distinct()
        subclient_locations = SubcompanyDetails.objects.filter(parent_company=client).values_list('location_id').distinct()

        locations = set(jobposting_locations) | set(client_locations) | set(subclient_locations)

        location_list = list(locations)
        return JsonResponse(location_list, safe=False)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)


def get_client_details(request):
    if request.method == 'GET':
        client = request.GET.get('client')
        try:
            # Retrieve a single ClientDetails object
            client_obj = ClientDetails.objects.get(parent_company=client)
            client_data = {
                'parent_company': client_obj.parent_company,
                'GST_No': client_obj.GST_No,
                'Location_Id': client_obj.location_Id,
                'Address_1': client_obj.address_1,
                'Address_2': client_obj.address_2,
                'City': client_obj.City,
                'State': client_obj.state,
                'Pincode': client_obj.Pincode,
                'Country': client_obj.country
            }
            return JsonResponse(client_data)
        except ClientDetails.DoesNotExist:
            return JsonResponse({'error': 'Client not found'}, status=404)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)

def new_login(request):
    if request.method == 'POST':
        Login_id = request.POST.get('phone')
        password = request.POST.get('password')

        print(Login_id, password)

        user = InternalTeam.objects.filter(Login=Login_id,Password=password).first()
        print(user)
        if user is not None:

            print(user.user_id)
            return redirect('dashboard', user_id=user.user_id)

        else:
            messages.error(request, 'Invalid phone number or password.')

    return render(request, 'user/home.html')

def new_job_posting(request):
    clients = ClientDetails.objects.all()
    user_id = request.GET.get('user_id', None)
    print('opened newJobPosting:',user_id)
    user = get_object_or_404(InternalTeam,user_id=user_id)
    print(user.Level)

    restricted =bool(int((user.Level)[6:]) < 5)

    if restricted==True:
        return render(request, 'user/new_job_posting.html', {'user': user, 'clients': clients, 'user_id': user_id, 'restricted': True})
    else:
        return render(request, 'user/new_job_posting.html', {'user': user,'clients': clients,'user_id': user_id, 'restricted': False})


def get_contacts(request):
    if request.method == 'GET':
        client = request.GET.get('Client')
        print(client)
        SPOC_Details = AddContact.objects.filter(Company=client).values('FirstName','LastName')

        SPOC_Details_list = list(SPOC_Details)
        return JsonResponse(SPOC_Details_list, safe=False)
    else:
        return JsonResponse({'error': 'Invalid request'})

def validate_field(request):
    if request.method == 'GET':
        email = request.GET.get('Email')
        phone_number = request.GET.get('Phone_number')
        response = {
            'exists': False
        }
        if email and AddContact.objects.filter(Email=email).exists():
            response['exists'] = True
        elif phone_number and AddContact.objects.filter(Phone_number=phone_number).exists():
            response['exists'] = True
        return JsonResponse(response)


def all_job_postings(request):
    user_id = request.GET.get('user_id', None)
    print('opened allJobPosting:', user_id)
    clients = ClientDetails.objects.all()
    user = get_object_or_404(InternalTeam, user_id=user_id)
    print(user.Level)

    restricted = bool(int((user.Level)[6:]) < 5)

    if restricted == True:
        job_postings = JobPosting.objects.all()
        return render(request, 'user/all_job_postings.html',
                      {'user': user, 'clients': clients, 'user_id': user_id, 'restricted': True,'job_postings': job_postings})
    else:
        query = request.GET.get('query', '')  # Get the query parameter if it exists

        if query:
            job_postings = (JobPosting.objects.filter(job_id__icontains=query) |
                            JobPosting.objects.filter(spoc__icontains=query) |
                            JobPosting.objects.filter(client__icontains=query ))
        else:
            job_postings = JobPosting.objects.all()

        return render(request, 'user/all_job_postings.html',
            {'user': user, 'clients': clients, 'user_id': user_id, 'restricted': False,'job_postings': job_postings})


def get_jobPosting(request):
    if request.method == 'GET':
        jobId = request.GET.get('JobId')
        try:
            # Retrieve a single ClientDetails object
            job_obj = JobPosting.objects.get(JobID=jobId)
            job_data = {
                'Client': job_obj.Client,
                'JobID': job_obj.JobID,
                'Location': job_obj.Location,
                'SPOC': job_obj.SPOC,
                'SPOC2': job_obj.SPOC2,
                'NoOfPosting': job_obj.NoOfPosting,
                'StartDate': job_obj.StartDate,
                'CloseDate': job_obj.CloseDate,
                'Experience_in_Yrs': job_obj.Experience_in_Yrs,
                'BudgetMin': job_obj.BudgetMin,
                'Qualification': job_obj.Qualification,
                'Header': job_obj.Header,
                'JobDescription': job_obj.JobDescription,
                'SpecialInstructions': job_obj.SpecialInstructions
            }
            return JsonResponse(job_data)
        except JobPosting.DoesNotExist:
            return JsonResponse({'error': 'Job Posting not found'}, status=404)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)


def messages(request):
    user_id= request.GET.get('úser_id')
    return render(request, 'user/Messages.html',{'user_id': user_id})