import os
import platform

from django import get_version as django_version
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .models import Category, Shop, Product

def home(request):
    """Render the marketplace landing page with search and filter."""
    categories = Category.objects.all()
    
    # Get query parameters
    query = request.GET.get('q', '')
    category_slug = request.GET.get('category', '')
    
    products = Product.objects.filter(is_active=True).order_by('-created_at')
    
    if query:
        products = products.filter(name__icontains=query)
    
    if category_slug:
        products = products.filter(category__slug=category_slug)
    
    featured_products = products[:12] # Show more products on home
    
    context = {
        "categories": categories,
        "featured_products": featured_products,
        "query": query,
        "selected_category": category_slug,
        "current_time": timezone.now(),
    }
    return render(request, "core/index.html", context)

def product_detail(request, slug):
    """Render the product detail page."""
    product = get_object_or_404(Product, slug=slug, is_active=True)
    return render(request, "core/product_detail.html", {"product": product})

def shop_list(request):
    """Render a list of all shops."""
    shops = Shop.objects.all().order_by('name')
    return render(request, "core/shop_list.html", {"shops": shops})

def shop_detail(request, slug):
    """Render a specific shop's page with its products."""
    shop = get_object_or_404(Shop, slug=slug)
    products = Product.objects.filter(shop=shop, is_active=True)
    return render(request, "core/shop_detail.html", {"shop": shop, "products": products})

@login_required
def dashboard(request):
    """Seller dashboard showing their shops and products."""
    shops = Shop.objects.filter(owner=request.user)
    products = Product.objects.filter(shop__owner=request.user).order_by('-created_at')
    
    context = {
        "shops": shops,
        "products": products,
    }
    return render(request, "core/dashboard/index.html", context)

@login_required
def shop_add(request):
    """Add a new shop."""
    if request.method == "POST":
        name = request.POST.get('name')
        description = request.POST.get('description')
        whatsapp_number = request.POST.get('whatsapp_number')
        logo = request.FILES.get('logo')
        
        Shop.objects.create(
            owner=request.user,
            name=name,
            description=description,
            whatsapp_number=whatsapp_number,
            logo=logo
        )
        return redirect('dashboard')
        
    return render(request, "core/dashboard/shop_form.html", {
        "title": "Tambah Toko Baru"
    })

@login_required
def shop_edit(request, pk):
    """Edit an existing shop."""
    shop = get_object_or_404(Shop, pk=pk, owner=request.user)
    
    if request.method == "POST":
        shop.name = request.POST.get('name')
        shop.description = request.POST.get('description')
        shop.whatsapp_number = request.POST.get('whatsapp_number')
        if request.FILES.get('logo'):
            shop.logo = request.FILES.get('logo')
        
        shop.save()
        return redirect('dashboard')
        
    return render(request, "core/dashboard/shop_form.html", {
        "shop": shop,
        "title": "Edit Toko"
    })

@login_required
def product_add(request):
    """Add a new product."""
    shops = Shop.objects.filter(owner=request.user)
    categories = Category.objects.all()
    
    if request.method == "POST":
        shop_id = request.POST.get('shop')
        category_id = request.POST.get('category')
        name = request.POST.get('name')
        description = request.POST.get('description')
        price = request.POST.get('price')
        stock = request.POST.get('stock')
        image = request.FILES.get('image')
        
        shop = get_object_or_404(Shop, id=shop_id, owner=request.user)
        category = get_object_or_404(Category, id=category_id)
        
        Product.objects.create(
            shop=shop,
            category=category,
            name=name,
            description=description,
            price=price,
            stock=stock,
            image=image
        )
        return redirect('dashboard')
        
    return render(request, "core/dashboard/product_form.html", {
        "shops": shops,
        "categories": categories,
        "title": "Tambah Produk Baru"
    })

@login_required
def product_edit(request, pk):
    """Edit an existing product."""
    product = get_object_or_404(Product, pk=pk, shop__owner=request.user)
    shops = Shop.objects.filter(owner=request.user)
    categories = Category.objects.all()
    
    if request.method == "POST":
        product.shop = get_object_or_404(Shop, id=request.POST.get('shop'), owner=request.user)
        product.category = get_object_or_404(Category, id=request.POST.get('category'))
        product.name = request.POST.get('name')
        product.description = request.POST.get('description')
        product.price = request.POST.get('price')
        product.stock = request.POST.get('stock')
        if request.FILES.get('image'):
            product.image = request.FILES.get('image')
        
        product.save()
        return redirect('dashboard')
        
    return render(request, "core/dashboard/product_form.html", {
        "product": product,
        "shops": shops,
        "categories": categories,
        "title": "Edit Produk"
    })

@login_required
def product_delete(request, pk):
    """Delete a product."""
    product = get_object_or_404(Product, pk=pk, shop__owner=request.user)
    if request.method == "POST":
        product.delete()
    return redirect('dashboard')
