from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from catalog.models import Category, Product, ProductImage
from catalog.forms import CategoryForm, ProductForm, ProductImageForm
from django.forms import modelformset_factory

def staff_required(view):
    return user_passes_test(lambda u: u.is_active and u.is_staff)(view)

def admin_login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)
        if user and user.is_staff:
            login(request, user)
            return redirect("admin_dashboard")
        messages.error(request, "نام کاربری یا رمزعبور نادرست است.")
    return render(request, "adminpanel/login.html")

def admin_logout(request):
    logout(request)
    return redirect("admin_login")

@login_required
@staff_required
def dashboard(request):
    stats = {
        "categories": Category.objects.count(),
        "products": Product.objects.count(),
        "in_stock": Product.objects.filter(in_stock=True).count(),
    }
    return render(request, "adminpanel/dashboard.html", {"stats":stats})

@login_required
@staff_required
def category_list(request):
    items = Category.objects.select_related("parent").order_by("name")
    return render(request, "adminpanel/categories_list.html", {"items":items})

@login_required
@staff_required
def category_create(request):
    form = CategoryForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        form.save()
        messages.success(request, "دسته با موفقیت ثبت شد.")
        return redirect("admin_categories")
    return render(request, "adminpanel/category_form.html", {"form": form, "mode":"create"})

@login_required
@staff_required
def category_edit(request, pk):
    obj = get_object_or_404(Category, pk=pk)
    form = CategoryForm(request.POST or None, instance=obj)
    if request.method == "POST" and form.is_valid():
        form.save()
        messages.success(request, "تغییرات ذخیره شد.")
        return redirect("admin_categories")
    return render(request, "adminpanel/category_form.html", {"form": form, "mode":"edit", "obj":obj})

@login_required
@staff_required
def category_delete(request, pk):
    obj = get_object_or_404(Category, pk=pk)
    if request.method == "POST":
        obj.delete()
        messages.success(request, "حذف شد.")
        return redirect("admin_categories")
    return render(request, "adminpanel/confirm_delete.html", {"obj":obj, "type":"category"})

@login_required
@staff_required
def product_list(request):
    items = Product.objects.select_related("category").order_by("-id")
    return render(request, "adminpanel/products_list.html", {"items":items})

@login_required
@staff_required
def product_create(request):
    form = ProductForm(request.POST or None, request.FILES or None)
    ImageFormSet = modelformset_factory(ProductImage, form=ProductImageForm, extra=3, can_delete=True)
    formset = ImageFormSet(queryset=ProductImage.objects.none(), data=request.POST or None, files=request.FILES or None, prefix="imgs")
    if request.method == "POST" and form.is_valid() and formset.is_valid():
        product = form.save()
        for f in formset:
            if f.cleaned_data and not f.cleaned_data.get("DELETE", False):
                img = f.save(commit=False)
                img.product = product
                img.save()
        messages.success(request, "محصول ایجاد شد.")
        return redirect("admin_products")
    return render(request, "adminpanel/product_form.html", {"form":form, "formset":formset, "mode":"create"})

@login_required
@staff_required
def product_edit(request, pk):
    product = get_object_or_404(Product, pk=pk)
    form = ProductForm(request.POST or None, request.FILES or None, instance=product)
    ImageFormSet = modelformset_factory(ProductImage, form=ProductImageForm, extra=1, can_delete=True)
    formset = ImageFormSet(queryset=product.images.all(), data=request.POST or None, files=request.FILES or None, prefix="imgs")
    if request.method == "POST" and form.is_valid() and formset.is_valid():
        product = form.save()
        for f in formset:
            if f.cleaned_data:
                if f.cleaned_data.get("DELETE", False) and f.instance.pk:
                    f.instance.delete()
                else:
                    img = f.save(commit=False)
                    img.product = product
                    img.save()
        messages.success(request, "تغییرات ذخیره شد.")
        return redirect("admin_products")
    return render(request, "adminpanel/product_form.html", {"form":form, "formset":formset, "mode":"edit", "obj":product})

@login_required
@staff_required
def product_delete(request, pk):
    obj = get_object_or_404(Product, pk=pk)
    if request.method == "POST":
        obj.delete()
        messages.success(request, "حذف شد.")
        return redirect("admin_products")
    return render(request, "adminpanel/confirm_delete.html", {"obj":obj, "type":"product"})
# admin view (add)
# e.g. storefront/admin_views.py
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import get_user_model
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render

User = get_user_model()

@login_required
@user_passes_test(lambda u: u.is_staff)
def user_list(request):
    q = (request.GET.get("q") or "").strip()
    qs = User.objects.all().order_by("-date_joined")
    if q:
        qs = qs.filter(
            Q(username__icontains=q) |
            Q(email__icontains=q) |
            Q(first_name__icontains=q) |
            Q(last_name__icontains=q)
        )
    page_obj = Paginator(qs, 20).get_page(request.GET.get("page"))
    return render(request, "adminpanel/user_list.html", {"page_obj": page_obj, "q": q})
