"""
Wishlist API Views
"""
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from accounts.models import Wishlist
from products.models import Product


@require_http_methods(["POST"])
def toggle_wishlist(request, product_id):
    """Toggle product in wishlist (add/remove)"""
    # Check authentication and return JSON for AJAX requests
    if not request.user.is_authenticated:
        return JsonResponse({
            'success': False,
            'message': 'Please login to add items to wishlist',
            'require_login': True
        }, status=401)
    
    try:
        product = Product.objects.get(id=product_id)
        
        # Check if product is already in wishlist
        wishlist_item = Wishlist.objects.filter(
            user=request.user,
            product=product
        ).first()
        
        if wishlist_item:
            # Remove from wishlist
            wishlist_item.delete()
            return JsonResponse({
                'success': True,
                'added': False,
                'message': 'Removed from wishlist'
            })
        else:
            # Add to wishlist
            Wishlist.objects.create(
                user=request.user,
                product=product
            )
            return JsonResponse({
                'success': True,
                'added': True,
                'message': 'Added to wishlist'
            })
            
    except Product.DoesNotExist:
        return JsonResponse({
            'success': False,
            'message': 'Product not found'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': str(e)
        }, status=500)


def get_wishlist_count(request):
    """Get count of items in wishlist"""
    if not request.user.is_authenticated:
        return JsonResponse({'success': False, 'require_login': True}, status=401)
    count = Wishlist.objects.filter(user=request.user).count()
    return JsonResponse({'count': count, 'success': True})


def get_wishlist_items(request):
    """Get all wishlist items for current user"""
    if not request.user.is_authenticated:
        return JsonResponse({'success': False, 'require_login': True}, status=401)
    wishlist_items = Wishlist.objects.filter(user=request.user).select_related('product')
    
    items = []
    for item in wishlist_items:
        product = item.product
        items.append({
            'id': item.id,
            'product_id': product.id,
            'product_name': product.name,
            'product_slug': product.slug,
            'price': float(product.price),
            'sale_price': float(product.sale_price) if product.sale_price else None,
            'on_sale': product.on_sale,
            'in_stock': product.is_active and (not product.track_inventory or product.stock > 0),
            'image_url': product.featured_image.url if product.featured_image else None,
            'added_at': item.added_at.isoformat()
        })
    
    return JsonResponse({'items': items, 'success': True})


@require_http_methods(["POST"])
def remove_from_wishlist(request, product_id):
    """Remove specific product from wishlist"""
    if not request.user.is_authenticated:
        return JsonResponse({'success': False, 'require_login': True}, status=401)
    try:
        wishlist_item = Wishlist.objects.get(
            user=request.user,
            product_id=product_id
        )
        wishlist_item.delete()
        
        return JsonResponse({
            'success': True,
            'message': 'Removed from wishlist'
        })
    except Wishlist.DoesNotExist:
        return JsonResponse({
            'success': False,
            'message': 'Item not in wishlist'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': str(e)
        }, status=500)


@require_http_methods(["POST"])
def clear_wishlist(request):
    """Clear all items from wishlist"""
    if not request.user.is_authenticated:
        return JsonResponse({'success': False, 'require_login': True}, status=401)
    try:
        Wishlist.objects.filter(user=request.user).delete()
        return JsonResponse({
            'success': True,
            'message': 'Wishlist cleared'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': str(e)
        }, status=500)
