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 django.core.paginator import Paginator
from .models import BackToBase
from bookings.models import Booking
from django.utils import timezone
class BackToBaseListView(LoginRequiredMixin, View):
    def get(self, request):
        qs = BackToBase.objects.all().select_related('booking', 'rider', 'customer').order_by('-created_at')
        
        # Filter by status (default: active/unresolved)
        status_filter = request.GET.get('status', 'active')
        if status_filter == 'active':
            qs = qs.filter(is_resolved=False)
        elif status_filter == 'resolved':
            qs = qs.filter(is_resolved=True)
        
        # Search
        q = request.GET.get('q')
        if q:
            qs = qs.filter(booking__booking_id__icontains=q) | qs.filter(customer__first_name__icontains=q) | qs.filter(booking__contact_mobile__icontains=q) | qs.filter(poc_mobile__icontains=q)

        # Date Filter
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')

        if start_date:
            qs = qs.filter(created_at__date__gte=start_date)
        if end_date:
            qs = qs.filter(created_at__date__lte=end_date)

        paginator = Paginator(qs, 20)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        
        return render(request, 'pages/back_to_base/list.html', {
            'page_obj': page_obj, 
            'query': q,
            'status_filter': status_filter,
            'start_date': start_date,
            'end_date': end_date
        })

class BackToBaseCreateView(LoginRequiredMixin, View):
    def get(self, request):
        # Show bookings that are likely candidates (e.g., In Progress, or not Completed)
        # Or just all for flexibility. Let's show recent 100 non-completed/cancelled?
        bookings = Booking.objects.exclude(booking_status__in=['completed', 'cancelled']).order_by('-created_at')[:100]
        return render(request, 'pages/back_to_base/form.html', {'bookings': bookings})

    def post(self, request):
        booking_id = request.POST.get('booking')
        poc_name = request.POST.get('poc_name')
        poc_mobile = request.POST.get('poc_mobile')
        reason = request.POST.get('reason')
        
        if not booking_id:
            messages.error(request, "Please select a booking.")
            return redirect('back-to-base-create')

        booking = get_object_or_404(Booking, pk=booking_id)
        
        BackToBase.objects.create(
            booking=booking,
            rider=booking.rider,
            customer=booking.user,
            poc_name=poc_name,
            poc_mobile=poc_mobile,
            reason=reason
        )
        messages.success(request, 'Back to Base entry created.')
        return redirect('back-to-base-list')

class BackToBaseEditView(LoginRequiredMixin, View):
    def get(self, request, pk):
        entry = get_object_or_404(BackToBase, pk=pk)
        return render(request, 'pages/back_to_base/edit.html', {'entry': entry})

    def post(self, request, pk):
        entry = get_object_or_404(BackToBase, pk=pk)
        entry.poc_name = request.POST.get('poc_name')
        entry.poc_mobile = request.POST.get('poc_mobile')
        entry.reason = request.POST.get('reason')
        entry.save()
        messages.success(request, 'Back to Base entry updated.')
        return redirect('back-to-base-list')

class BackToBaseResolveView(LoginRequiredMixin, View):
    def post(self, request, pk):
        entry = get_object_or_404(BackToBase, pk=pk)
        if not entry.is_resolved:
            entry.is_resolved = True
            entry.resolved_at = timezone.now()
            entry.save()
            messages.success(request, 'Back to Base entry resolved.')
        else:
            messages.info(request, 'Entry is already resolved.')
        return redirect('back-to-base-list')


