from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Sum
from django.shortcuts import redirect, render

from orders.models import Order
from products.models import WishlistItem


def login_view(request):
    if request.user.is_authenticated:
        return redirect('profile')

    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()

        if not username or not password:
            return render(request, 'accounts/login.html', {'error': 'Username and password are required'})

        user = authenticate(request, username=username, password=password)

        if user:
            login(request, user)
            messages.success(request, f'Welcome back, {username}!')
            return redirect('profile')

        return render(request, 'accounts/login.html', {'error': 'Invalid username or password. Please check and try again.'})

    return render(request, 'accounts/login.html')


def register_view(request):
    if request.user.is_authenticated:
        return redirect('profile')

    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        confirm_password = request.POST.get('confirm_password', '').strip()
        email = request.POST.get('email', '').strip()
        register_as_seller = request.POST.get('register_as_seller') == 'on'

        if not username or not password or not confirm_password:
            return render(request, 'accounts/register.html', {'error': 'All fields are required', 'username': username, 'email': email, 'register_as_seller': register_as_seller})
        if len(username) < 3:
            return render(request, 'accounts/register.html', {'error': 'Username must be at least 3 characters long', 'username': username, 'email': email, 'register_as_seller': register_as_seller})
        if len(password) < 6:
            return render(request, 'accounts/register.html', {'error': 'Password must be at least 6 characters long', 'username': username, 'email': email, 'register_as_seller': register_as_seller})
        if password != confirm_password:
            return render(request, 'accounts/register.html', {'error': 'Passwords do not match', 'username': username, 'email': email, 'register_as_seller': register_as_seller})
        if User.objects.filter(username=username).exists():
            return render(request, 'accounts/register.html', {'error': 'Username already exists', 'email': email, 'register_as_seller': register_as_seller})
        if email and User.objects.filter(email=email).exists():
            return render(request, 'accounts/register.html', {'error': 'Email already registered', 'username': username, 'register_as_seller': register_as_seller})

        user = User.objects.create_user(username=username, password=password, email=email)
        if register_as_seller:
            user.profile.is_seller = True
            user.profile.save(update_fields=['is_seller'])
        messages.success(request, 'Account created successfully! Please log in.')
        return redirect('login')

    return render(
        request,
        'accounts/register.html',
        {'register_as_seller': request.GET.get('seller') == '1'},
    )


def logout_view(request):
    logout(request)
    return redirect('/')


@login_required
def profile_view(request):
    user_orders = Order.objects.filter(user=request.user)
    delivered_orders = user_orders.filter(status='Delivered')
    recent_orders = user_orders.order_by('-created_at')[:5]

    total_spent = delivered_orders.aggregate(total=Sum('total_price')).get('total') or 0
    wishlist_count = WishlistItem.objects.filter(user=request.user).count()

    return render(
        request,
        'accounts/profile.html',
        {
            'user': request.user,
            'orders_count': user_orders.count(),
            'delivered_count': delivered_orders.count(),
            'pending_count': user_orders.exclude(status='Delivered').count(),
            'wishlist_count': wishlist_count,
            'total_spent': total_spent,
            'recent_orders': recent_orders,
        },
    )


@login_required
def edit_profile(request):
    from .forms import ProfileForm

    profile = getattr(request.user, 'profile', None)
    if profile is None:
        # ensure profile exists
        from .models import Profile

        profile = Profile.objects.create(user=request.user)

    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES, instance=profile)
        # populate user fields into form for display/save
        form.fields['first_name'].initial = request.user.first_name
        form.fields['last_name'].initial = request.user.last_name
        form.fields['email'].initial = request.user.email

        if form.is_valid():
            form.save()
            messages.success(request, 'Profile updated successfully.')
            return redirect('profile')
        else:
            messages.error(request, 'Please correct the errors below.')
    else:
        form = ProfileForm(instance=profile)
        form.fields['first_name'].initial = request.user.first_name
        form.fields['last_name'].initial = request.user.last_name
        form.fields['email'].initial = request.user.email

    return render(request, 'accounts/edit_profile.html', {'form': form, 'profile': profile})
