from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower

from .models import Class, Category
from .forms import ClassForm


def all_classes(request):
    """ A view to show all classes, including sorting and search queries """

    classes = Class.objects.all()
    query = None
    categories = None
    sort = None
    direction = None

    if request.GET:
        if 'sort' in request.GET:
            sortkey = request.GET['sort']
            sort = sortkey
            if sortkey == 'name':
                sortkey = 'lower_name'
                classes = classes.annotate(
                    lower_name=Lower('name'))
            if sortkey == 'category':
                sortkey = 'category__name'
            if 'direction' in request.GET:
                direction = request.GET['direction']
                if direction == 'desc':
                    sortkey = f'-{sortkey}'
            classes = classes.order_by(sortkey)

        if 'category' in request.GET:
            categories = request.GET['category'].split(',')
            classes = classes.filter(category__name__in=categories)
            categories = Category.objects.filter(name__in=categories)

        if 'q' in request.GET:
            query = request.GET['q']
            if not query:
                messages.error(
                    request, "You didn't enter any search criteria!")
                return redirect(reverse('classes'))

            queries = Q(
                name__icontains=query) | Q(description__icontains=query)
            classes = classes.filter(queries)

    current_sorting = f'{sort}_{direction}'

    context = {
        'classes': classes,
        'search_term': query,
        'current_categories': categories,
        'current_sorting': current_sorting,
    }

    return render(request, 'classes/classes.html', context)


def class_detail(request, class_id):
    """ A view to show individual class details """

    a_class = get_object_or_404(Class, pk=class_id)

    context = {
        'class': a_class,
    }

    return render(request, 'classes/class_detail.html', context)


@login_required
def add_class(request):
    """ Add a class to the store """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only store owners can do that.')
        return redirect(reverse('home'))

    if request.method == 'POST':
        form = ClassForm(request.POST, request.FILES)
        if form.is_valid():
            a_class = form.save()
            messages.success(request, 'Successfully added class!')
            return redirect(reverse('class_detail', args=[a_class.id]))
        else:
            messages.error(request, 'Failed to add class. Please ensure the form is valid.')
    else:
        form = ClassForm()

    template = 'classes/add_class.html'
    context = {
        'form': form,
    }

    return render(request, template, context)


@login_required
def edit_class(request, class_id):
    """ Edit a class in the store """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only store owners can do that.')
        return redirect(reverse('home'))

    a_class = get_object_or_404(Class, pk=class_id)
    if request.method == 'POST':
        form = ClassForm(request.POST, request.FILES, instance=a_class)
        if form.is_valid():
            form.save()
            messages.success(request, 'Successfully updated class!')
            return redirect(reverse('class_detail', args=[a_class.id]))
        else:
            messages.error(request, 'Failed to update class. Please ensure the form is valid.')
    else:
        form = ClassForm(instance=a_class)
        messages.info(request, f'You are editing {a_class.name}')

    template = 'classes/edit_class.html'
    context = {
        'form': form,
        'class': a_class,
    }

    return render(request, template, context)


@login_required
def delete_class(request, class_id):
    """ Delete a class from the store """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only store owners can do that.')
        return redirect(reverse('home'))

    bag = request.session.get('bag', {})
    bag.clear()
    a_class = get_object_or_404(Class, pk=class_id)
    a_class.delete()
    messages.success(request, 'Class deleted!')
    return redirect(reverse('classes'))
