from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from .models import ServiceRequest
from .forms import ServiceRequestForm
from django.db.models import Q
from datetime import datetime

class ServiceRequestManagementView(LoginRequiredMixin, View):
    def get(self, request):
        qs = ServiceRequest.objects.filter(trash=False).select_related('user', 'category')
        
        # Filters
        q = request.GET.get('q')
        status = request.GET.get('status')
        date_from = request.GET.get('date_from')
        date_to = request.GET.get('date_to')
        
        if q:
            qs = qs.filter(
                Q(request_id__icontains=q) | 
                Q(contact_mobile__icontains=q) |
                Q(contact_name__icontains=q) |
                Q(user__username__icontains=q) |
                Q(user__first_name__icontains=q) |
                Q(user__last_name__icontains=q)
            )
        if status:
            qs = qs.filter(status=status)
        
        if date_from:
            try:
                df = datetime.strptime(date_from, '%Y-%m-%d').date()
                qs = qs.filter(created_at__date__gte=df)
            except ValueError:
                pass
        if date_to:
            try:
                dt = datetime.strptime(date_to, '%Y-%m-%d').date()
                qs = qs.filter(created_at__date__lte=dt)
            except ValueError:
                pass
            
        return render(request, 'pages/service-request-management/service_request_list.html', {
            'requests': qs,
            'status_choices': ServiceRequest.STATUS_CHOICES,
            'query': q,
            'status': status,
            'date_from': date_from,
            'date_to': date_to
        })

class ServiceRequestDetailView(LoginRequiredMixin, View):
    def get(self, request, pk):
        service_request = get_object_or_404(ServiceRequest, pk=pk)
        return render(request, 'pages/service-request-management/service_request_detail.html', {
            'service_request': service_request,
            'status_choices': ServiceRequest.STATUS_CHOICES
        })

    def post(self, request, pk):
        service_request = get_object_or_404(ServiceRequest, pk=pk)
        
        # Update status
        new_status = request.POST.get('status')
        if new_status:
            service_request.status = new_status
        
        # Update Price
        new_price = request.POST.get('total_price')
        if new_price:
            try:
                service_request.total_price = float(new_price)
            except ValueError:
                pass

        service_request.save()
        messages.success(request, 'Request updated successfully.')
            
        return redirect('service-request-detail', pk=pk)

class ServiceRequestDeleteView(LoginRequiredMixin, View):
    def post(self, request, pk):
        service_request = get_object_or_404(ServiceRequest, pk=pk)
        service_request.trash = True
        service_request.save()
        messages.success(request, 'Service request deleted successfully.')
        return redirect('service-request-management')

class ServiceRequestUpdateView(LoginRequiredMixin, View):
    def get(self, request, pk):
        service_request = get_object_or_404(ServiceRequest, pk=pk)
        form = ServiceRequestForm(instance=service_request)
        return render(request, 'pages/service-request-management/service_request_edit.html', {
            'form': form,
            'service_request': service_request
        })

    def post(self, request, pk):
        service_request = get_object_or_404(ServiceRequest, pk=pk)
        form = ServiceRequestForm(request.POST, instance=service_request)
        if form.is_valid():
            form.save()
            messages.success(request, 'Service request updated successfully.')
            return redirect('service-request-detail', pk=pk)
        return render(request, 'pages/service-request-management/service_request_edit.html', {
            'form': form,
            'service_request': service_request
        })
