from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.utils import timezone
from django.views import View
from django.views.generic import CreateView, UpdateView, FormView, ListView

from booking.models import Booking
from common.utils.utils import get_container_by_number
from containers.forms import ContainerReceiveForm, ContainerExpeditionForm
from containers.models import Container
from containers.services import get_container_for_booking
from preinfo.models import Preinfo


# Create your views here.
class ContainerReceive(CreateView):
    template_name = 'container-receive.html'
    model = Container
    form_class = ContainerReceiveForm
    success_url = reverse_lazy('dashboard')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pk = self.kwargs.get('pk')
        try:
            preinfo =Preinfo.objects.filter(pk=pk, received=False).first()
        except Preinfo.DoesNotExist:
            preinfo = None

        if preinfo:
            context['preinfo'] = preinfo
            context['containers'] = Container.objects.order_by('-received_on').all()[:10]  # Fetch the last 10 containers
            return context
        return redirect(reverse_lazy('container_search'))

    def form_valid(self, form):

        # Get the preinfo_id from the POST data
        preinfo_id = self.request.POST.get('preinfo_id')
        try:
            preinfo = Preinfo.objects.get(id=preinfo_id)
        except Preinfo.DoesNotExist:
            preinfo = None

        # validate if data is correct, comparing user data with preinfo data
        if preinfo and preinfo.container_number == form.cleaned_data.get('number') and not preinfo.received:
            preinfo.received = True
            preinfo.save()

            form.instance.received_by = self.request.user
            form.instance.line = preinfo.line
            form.instance.container_type = preinfo.container_type
        else:
            form.add_error('number', 'Invalid data')

        return super().form_valid(form)


class ContainerSearchView(View):
    template_name = 'container-search.html'

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request):
        booking = Booking.objects.get(number=request.POST.get('number'))
        if not booking:
            return render(request, self.template_name, {'error': 'Booking not found'})

        filters = {
            'expedited': False,
        }
        if booking.container_number:
            filters['container_number'] = booking.container_number
        else:
            filters['container_type'] = booking.container_type
            filters['line'] = booking.line

        container = Container.objects.filter(**filters).order_by('received_on').first()
        if not container:
            return render(request, self.template_name, {'error': 'Not found'})
        next_url = request.POST.get('param')
        return redirect(next_url, pk=booking.pk)


class ContainerExpedition(UpdateView):
    template_name = 'container-expedition.html'
    model = Container
    form_class = ContainerExpeditionForm
    success_url = reverse_lazy('dashboard')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pk = self.kwargs.get('pk')
        booking = Booking.objects.get(pk=pk)
        filters = {
            'expedited': False,
        }
        if booking.container_number:
            filters['container_number'] = booking.container_number
        else:
            filters['container_type'] = booking.container_type
            filters['line'] = booking.line

        container = Container.objects.filter(**filters).order_by('received_on').first()
        context['container'] = container
        context['booking'] = booking
        return context

    def form_valid(self, form):
        booking_id = self.request.POST.get('booking_id')
        container_id = self.request.POST.get('container_id')

        try:
            booking = Booking.objects.get(id=booking_id)
            container = Container.objects.get(id=container_id)
            vehicle = form.cleaned_data['expedition_vehicle']
            # Update container
            container.expedited = True
            container.expedited_on = timezone.now()
            container.expedited_by = self.request.user
            container.expedition_vehicle = vehicle
            container.booking = booking
            container.save()

            # Update booking status if needed
            booking.container_expedited_count += 1
            if booking.vehicles:
                vehicles_list = booking.vehicles.split(',')
                if vehicle in vehicles_list:
                    vehicles_list.remove(vehicle)
                    booking.vehicles = ','.join(vehicles_list)
            if booking.container_expedited_count >= booking.container_count:
                booking.status = 'completed'  # or any other status you want to set
            booking.save()

            return redirect(self.success_url)

        except (Booking.DoesNotExist, Container.DoesNotExist):
            form.add_error(None, 'Invalid booking or container')
            return self.form_invalid(form)


        # try:
        #     booking = Booking.objects.get(id=booking_id)
        # except Booking.DoesNotExist:
        #     booking = None
        # # validate if data is correct, comparing user data with booking data
        # if booking and booking.container_number == form.cleaned_data.get('container_number') and not booking.expedited:
        #     booking.expedited = True
        #     booking.save()
        #
        #     form.instance.expedited_by = self.request.user
        #     form.instance.line = booking.line
        #     form.instance.container_type = booking.container_type
        # else:
        #     form.add_error('container_number', 'Invalid data')

        # if preinfo:
        #     context['preinfo'] = preinfo
        #     context['containers'] = Container.objects.order_by('-received_on').all()[:10]  # Fetch the last 10 containers
        #     return context
        # return redirect(reverse_lazy('container_search'))

