from django.shortcuts import render, redirect,HttpResponse,get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_decode
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import User,Service,ServiceRequest 
from .forms import UserRegistrationForm
from django.urls import reverse
import logging
import json
from django.utils import timezone
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect


logger = logging.getLogger('main')
def home(request):
    if(request.method == "GET"):
        category = request.GET.get('category')
        search = request.GET.get('search')
        services = Service.objects.all()
        if category:
            try:
                service = Service.objects.get(id=category)
                service_providers = User.objects.filter(service_offered=service)
            except Service.DoesNotExist:
                service_providers = []
        elif search:
            try:
                service_providers = User.objects.filter(first_name__startswith=search)
            except Service.DoesNotExist:
                service_providers = []
        else:
            service_providers = User.objects.filter(service_offered__isnull=False)
        context = {
            'service_providers': service_providers,
            'services': services
        }

        return render(request, "main/home.html", context)
    print(request.POST)
    return HttpResponse("<h1>tjisfjsa<h1>")

def register(request):
    if request.user.is_authenticated:
        messages.warning(request, "You are already logged in.")
        return redirect('home')

    if request.method == 'POST':
        form = UserRegistrationForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                user = form.save()
                messages.success(request, 'Registration successful! You can now login.')
                return redirect('login')
            except Exception as e:
                logger.error(f"Registration error: {str(e)}")
                messages.error(request, 'An error occurred during registration. Please try again.')
        else:
            # Display form errors
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f"{field}: {error}")
    else:
        form = UserRegistrationForm()

    return render(request, 'main/register.html', {'form': form})
def activate_account(request, uidb64, token):
    try:
        uid = urlsafe_base64_decode(uidb64).decode()
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and default_token_generator.check_token(user, token):
        user.is_active = True
        user.save()
        messages.success(request, 'Your account has been activated. You can now log in.')
        return redirect('login')
    else:
        messages.error(request, 'Invalid activation link.')
        return redirect('register')

def user_login(request):
    if request.user.is_authenticated:
        messages.info(request, f'You are already logged in as {request.user}')
        return redirect('home')
    else:
        if request.method == 'POST':
            email = request.POST['email']
            password = request.POST['password']

            # Authenticate the user using the email and password
            user = authenticate(request, email=email, password=password)

            if user is not None:
                # Log the user in
                login(request, user)
                messages.success(request, f'Welcome {user}!')
                return redirect('home')
            else:
                # If authentication fails
                messages.error(request, 'Invalid email or password. Please try again.')

        # Handle GET request by initializing a blank form
        form = None  # Optionally, you can replace this with your login form
        return render(request, 'main/login.html', {'form': form})    

@login_required(login_url='login')
def user_logout(request):
    logout(request)
    messages.success(request, 'You have been logged out.')
    return redirect('login')

def services(request):
    return render(request,'main/services1.html')

@login_required(login_url='login')
@csrf_protect
def hire_view(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            price = data.get('price')
            initiator_id = data.get('initiator')
            service_provider_id = data.get('serviceProvider')
            service_hour = data.get('serviceHour')
            caretakerservice_id = data.get('caretakerservice')

            # Validate required fields
            if not price or not initiator_id or not service_provider_id or not service_hour or not caretakerservice_id:
                return JsonResponse({'error': 'Missing required fields'}, status=400)

            # Validate initiator
            if str(request.user.id) != str(initiator_id):
                return JsonResponse({'error': 'Unauthorized initiator'}, status=401)

            # Retrieve service provider and service
            service_provider = get_object_or_404(User, id=service_provider_id)
            service = get_object_or_404(Service, id=caretakerservice_id)

            # Create and save the service request
            service_request = ServiceRequest(
                agreed_price=price,
                service_provider=service_provider,
                client=request.user,
                service_hour=service_hour,
                service=service
            )
            service_request.save()

            messages.success(request, 'Request submitted successfully!')
            return JsonResponse({'success': 'Request submitted successfully!'}, status=201)

        except json.JSONDecodeError:
            messages.error(request, 'Invalid JSON format')
            return JsonResponse({'error': 'Invalid JSON format'}, status=400)
        except User.DoesNotExist:
            messages.error(request, 'Service provider does not exist')
            return JsonResponse({'error': 'Service provider does not exist'}, status=404)
        except Service.DoesNotExist:
            messages.error(request, 'Service does not exist')
            return JsonResponse({'error': 'Service does not exist'}, status=404)
        except Exception as e:
            messages.error(request, f'An error occurred: {str(e)}')
            return JsonResponse({'error': 'An error occurred'}, status=500)
    else:
        messages.error(request, 'Invalid request method')
        return JsonResponse({'error': 'Invalid request method'}, status=405)

@login_required(login_url='login')
def profie_View(request,pk):
    if request.method == "GET":
        user = get_object_or_404(User,id=pk)
        pending_requests = ServiceRequest.objects.filter(service_provider=user, is_approved=False)
        current = ServiceRequest.objects.filter(service_provider=user, is_approved=True, is_completed=False)
        completed = ServiceRequest.objects.filter(service_provider=user, is_completed=True)
        context = {'user':user,
        'pending_requests':pending_requests,
        'completed_orders' : completed,
        'current':current,
                   }
        return render(request,'main/profile.html', context)

login_required(login_url='login')
def approve(request, pk):
    try:
        instance = ServiceRequest.objects.get(id=pk)
    except ServiceRequest.DoesNotExist:
        return redirect('error_page')
    instance.is_approved = True
    instance.agreed_on = timezone.now()
    instance.save()
    profile_url = reverse('profiles', kwargs={'pk': request.user.id})
    return redirect(profile_url)


def complete(request, pk):
    print(pk)
    try:
        instance = ServiceRequest.objects.get(id=pk)
    except ServiceRequest.DoesNotExist:
        return redirect('error_page')
    instance.completed_date = timezone.now()
    instance.is_completed = True
    instance.save()
    print(instance.is_completed)
    profile_url = reverse('profiles', kwargs={'pk': request.user.id})
    print(profile_url)
    return redirect(profile_url)

