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, ContainerPhotos
from containers.services import get_container_for_booking
from preinfo.models import Preinfo


# Create your views here.
class ContainerReceiveView(FormView):
    template_name = 'container-receive.html'
    form_class = ContainerReceiveForm
    success_url = reverse_lazy('container_photos')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['show_search'] = True

        search_number = self.request.GET.get('number')
        if search_number:
            preinfo = Preinfo.objects.filter(container_number=search_number).first()
            if preinfo:
                form = self.form_class(initial={'number': preinfo.container_number})
                context.update({
                    'form': form,
                    'preinfo': preinfo,
                    'search_number': search_number,
                    'show_search': False
                })
            else:
                context.update({
                    'error': 'Preinfo for this container not found',
                    'search_number': search_number
                })
        return context

    def form_valid(self, form):
        container = form.save(commit=False)
        preinfo = Preinfo.objects.filter(container_number=self.request.POST.get('number')).first()
        preinfo.received = True
        preinfo.save()
        # Set required fields from preinfo
        container.container_type = preinfo.container_type
        container.line = preinfo.line
        container.received_by = self.request.user
        container.preinfo = preinfo
        container.save()

        return redirect('container_photos', pk=container.pk)

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        search_number = self.request.GET.get('number')  # Changed from search_number
        if search_number:
            preinfo = Preinfo.objects.filter(container_number=search_number).first()
            if preinfo:
                form.initial['number'] = preinfo.container_number
                form.fields['number'].widget.readonly = True
        return form

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(
            form=form,
            search_number=self.request.POST.get('number'),
            show_search=False
        ))


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'))


class ContainerExpedition(FormView):
    template_name = 'container-expedition.html'
    form_class = ContainerExpeditionForm
    success_url = reverse_lazy('barrier_dashboard')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['show_search'] = True

        search_number = self.request.GET.get('number')
        if search_number:
            booking = Booking.objects.filter(number=search_number).first()
            if booking:
                container = get_container_for_booking(booking)
                if container:
                    # Initialize form with container data
                    form = self.form_class(initial={
                        'number': container.number,
                        'position': container.position,
                        'line': container.line.id,
                        'container_type': container.container_type.id,
                        'damages': container.damages,
                        'heavy_damaged': container.heavy_damaged,
                        'expedition_vehicle': container.expedition_vehicle
                    })
                    context.update({
                        'form': form,
                        'booking': booking,
                        'container': container,
                        'search_number': search_number,
                        'show_search': False
                    })
                else:
                    context.update({
                        'error': 'No available container found for this booking',
                        'search_number': search_number
                    })
            else:
                context.update({
                    'error': 'Booking not found',
                    'search_number': search_number
                })
        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)

            # Update container
            container.expedited = True
            container.expedited_on = timezone.now()
            container.expedited_by = self.request.user
            container.expedition_vehicle = form.cleaned_data['expedition_vehicle']
            container.booking = booking
            container.save()

            # Update booking
            booking.container_expedited_count += 1
            if booking.vehicles:
                vehicles_list = booking.vehicles.split(',')
                if container.expedition_vehicle in vehicles_list:
                    vehicles_list.remove(container.expedition_vehicle)
                    booking.vehicles = ','.join(vehicles_list)
            if booking.container_expedited_count >= booking.container_count:
                booking.status = 'completed'
            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)

    def form_invalid(self, form):
        print("Form errors:", form.errors)  # Debug print
        print("Form data:", form.data)  # Debug print
        return self.render_to_response(self.get_context_data(
            form=form,
            search_number=self.request.POST.get('number'),
            show_search=False
        ))


    def get_form(self, form_class=None):
        form_class = self.get_form_class()

        if self.request.method == 'POST':
            search_number = self.request.POST.get('search_number')
            booking = Booking.objects.filter(number=search_number).first()
            if booking:
                container = get_container_for_booking(booking)
                if container:
                    data = self.request.POST.copy()
                    data.update({
                        'number': container.number,
                        'position': container.position,
                        'line': container.line,
                        'container_type': container.container_type,
                        'damages': container.damages,
                        'heavy_damaged': container.heavy_damaged,
                    })
                    return form_class(data)
        return form_class()




# containers/views/barrier_views.py
class ContainerPhotosView(View):
    template_name = 'container-photos.html'

    def get(self, request, pk):
        container = Container.objects.get(pk=pk)
        photos = ContainerPhotos.objects.filter(container=container)
        return render(request, self.template_name, {
            'container': container,
            'photos': photos,
            'photos_count': photos.count()
        })