from django.views.generic.edit import DeleteView
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib import messages
from store.models import Category, Product
from django.urls import reverse_lazy
from .forms import ProductForm, CouponForm, CategoryForm
from accounts.forms import RegisterForm
from accounts.models import User
from django.views.generic import ListView
from basket.models import Order
from django.views.generic.edit import UpdateView
from basket.models import Cart, CartItem, Coupon
from basket.views import _cart_id
# from django.template.loader import render_to_string
from django.core import serializers
# Create your views here.


def admin_login(request):
    if request.session.has_key('username'):
        return redirect('index')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        if username == 'ajmal_ahamed' and password == 'qwerty':
            request.session['username'] = username
            return redirect('index')
        else:
            messages.info(request, 'username or password is incorrect')
            return render(request, 'admin_login.html')
    return render(request, 'admin_login.html')


def admin_index(request):
    if request.session.has_key('username'):
        users = User.objects.all().count()
        products = Product.objects.all().count()
        orders_ = Order.objects.all().count()
        orders_placed = Order.objects.filter(order_status="Placed").count()
        order_cancelled = Order.objects.filter(
            order_status="Cancelled").count()
        order_delivered = Order.objects.filter(
            order_status="Delivered").count()
        order_returned = Order.objects.filter(order_status="Returned").count()
        total_users = User.objects.all().count()
        active_users = User.objects.filter(is_active=True).count()
        blocked_users = User.objects.filter(is_active=False).count()
        context = {
            'users': users,
            'products': products,
            'total_orders': orders_,
            'blocked': blocked_users
        }
        return render(request, 'dashboard.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'dashboard.html')


def admin_category(request):
    if request.session.has_key('username'):
        queryset = Category.objects.all()
        if request.method == 'POST':
            category = request.POST['add']
            slug = request.POST['slug']
            dis = request.POST['discount']
            Category.objects.create(
                name=category, slug=slug, discount=dis)
        context = {
            'categories': queryset
        }
        return render(request, 'category.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'categories.html')


def admin_category_edit(request, id):
    if request.session.has_key('username'):
        qs = get_object_or_404(Category, id=id)
        form = CategoryForm(instance=qs)
        if request.method == 'POST':
            form = CategoryForm(request.POST, instance=qs)
            if form.is_valid():
                form.save()
                messages.success(request, '1 Category Edited Successfully')
                return redirect('categories')
        context = {'form': form}
        return render(request, 'category_edit.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'category_edit.html')


def admin_category_delete(request):
    category_id = request.POST['id']
    category_delete = Category.objects.get(id=category_id)
    category_delete.delete()
    return JsonResponse({'success': True})


def admin_product_list(request):
    if request.session.has_key('username'):
        qs = Product.objects.all()
        context = {
            "product": qs
        }
        return render(request, 'product_list.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'product_list.html')


def admin_product_add(request):
    if request.session.has_key('username'):
        form = ProductForm()
        if request.method == 'POST':
            form = ProductForm(request.POST, request.FILES)
            if form.is_valid():
                category = form.cleaned_data.get('category')
                product_name = form.cleaned_data.get('product_name')
                product_desc = form.cleaned_data.get('product_desc')
                offer = form.cleaned_data.get('offer')
                product_price_1 = form.cleaned_data.get('product_price_1')
                slug = form.cleaned_data.get('slug')
                in_stock = form.cleaned_data.get('in_stock')

                product_image1 = form.cleaned_data.get('product_image1')
                product_image2 = form.cleaned_data.get('product_image2')
                product_image3 = form.cleaned_data.get('product_image3')
                if offer:
                    offer_total = int(product_price_1) - \
                        (int(product_price_1 * int(offer)/100))
                    create_product = Product(
                        category=category, product_name=product_name, product_desc=product_desc, offer=offer, product_price_1=product_price_1, product_price=offer_total, slug=slug, in_stock=in_stock, product_image1=product_image1, product_image2=product_image2, product_image3=product_image3)
                    create_product.save()
                else:
                    create_product = Product(
                        category=category, product_name=product_name, product_desc=product_desc, offer=None, product_price_1=product_price_1, product_price=product_price_1, slug=slug, in_stock=in_stock, product_image1=product_image1, product_image2=product_image2, product_image3=product_image3)
                    create_product.save()
                messages.success(request, 'Added 1 Product Successfully!')
                return HttpResponseRedirect(reverse_lazy('product_list'))
        context = {'form': form}
        return render(request, 'product.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'product.html')


def admin_product_edit(request, slug):
    if request.session.has_key('username'):
        qs = get_object_or_404(Product, slug=slug)
        form = ProductForm(instance=qs)
        if request.method == 'POST':
            form = ProductForm(request.POST, request.FILES, instance=qs)
            if form.is_valid():
                form.save()
                return redirect('product_list')
        context = {'form': form, 'product': qs}
        return render(request, 'product_edit.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'product_edit.html')


def admin_product_detail(request, slug):
    if request.session.has_key('username'):
        qs = get_object_or_404(Product, slug=slug)
        context = {'products': qs}
        return render(request, 'admin_product_detail.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'admin_product_detail.html', context)


def admin_product_delete(request):
    product_id = int(request.POST['id'])
    product = Product.objects.get(id=product_id)
    product.delete()
    return JsonResponse({'success': True})


def admin_coupon(request):
    form = CouponForm()
    if request.method == 'POST':
        form = CouponForm(request.POST)
        if form.is_valid():
            form.save()
            messages.info(request, "1 Coupon Added Successfully")
            return redirect('admin_coupon_list')
    context = {'form': form}
    return render(request, "new_coupon.html", context)


def admin_coupon_list(request):
    coupon = Coupon.objects.all()
    context = {'coupon': coupon}
    return render(request, 'coupon_list.html', context)


def coupon_edit(request, id):
    if request.session.has_key('username'):
        qs = get_object_or_404(Coupon, id=id)
        form = CouponForm(instance=qs)
        if request.method == 'POST':
            form = CouponForm(request.POST, instance=qs)
            if form.is_valid():
                form.save()
                messages.info(request, "1 Coupon Edited Successfully")
                return redirect('admin_coupon_list')
        context = {'form': form}
        return render(request, 'admin_coupon_edit.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'admin_coupon_edit.html')


def coupon_delete(request):
    coupon_id = request.POST['id']
    coupon_delete = Coupon.objects.get(id=coupon_id)
    coupon_delete.delete()
    return JsonResponse({'success': True})


def admin_user_list(request):
    if request.session.has_key('username'):
        qs = User.objects.all()
        context = {
            'user': qs
        }
        return render(request, 'user_list.html', context)
    else:
        return redirect('admin_login')
    return render(request, 'user_list.html')


def admin_user_block(request):
    user_id = request.GET['id']
    user = get_object_or_404(User, id=user_id)
    if user.is_active:
        user.is_active = False
    else:
        user.is_active = True
    return JsonResponse({'success': True})


def admin_order(request):
    qs = Order.objects.all()
    context = {'orders': qs}
    if len(qs) == 0:
        messages.info(request, 'No Orders Yet!')
    return render(request, 'admin_order.html', context)


def admin_order_status(request):
    order_id = int(request.GET['order_id'])
    order_status = request.GET['order_status']
    order = get_object_or_404(Order, id=order_id)
    order.order_status = order_status
    order.save()
    return JsonResponse({'status': order_status})


def order_reports(request):
    if request.method == 'POST':
        date_from = request.POST['datefrom']
        date_to = request.POST['dateto']
        order_search = Order.objects.filter(date__range=[date_from, date_to])
        return render(request, 'admin_reports.html', {'reports': order_search})
    else:
        order_search = Order.objects.all()
        return render(request, 'admin_reports.html', {'reports': order_search})


def admin_logout(request):
    if request.session.has_key('username'):
        request.session.flush()
        return redirect('admin_login')
    else:
        return redirect('admin_login')
