"""
Views for wallet app.
"""
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from .forms import WithdrawalRequestForm
from .models import Wallet, Transaction, TransactionStatus, TransactionType, WithdrawalRequest


@login_required
def wallet_overview_view(request):
    """
    View to display user's wallet overview.
    """
    wallet, created = Wallet.objects.get_or_create(user=request.user)
    
    # Get recent transactions
    recent_transactions = Transaction.objects.filter(wallet=wallet)[:10]
    
    context = {
        'wallet': wallet,
        'recent_transactions': recent_transactions,
        'recent_withdrawals': WithdrawalRequest.objects.filter(wallet=wallet)[:5],
    }
    return render(request, 'wallet/wallet_overview.html', context)


@login_required
def transaction_history_view(request):
    """
    View to display user's transaction history.
    """
    wallet = get_object_or_404(Wallet, user=request.user)
    transactions = Transaction.objects.filter(wallet=wallet).order_by('-created_at')
    
    # Filter by status
    status = request.GET.get('status')
    if status:
        transactions = transactions.filter(status=status)
    
    # Filter by type
    transaction_type = request.GET.get('type')
    if transaction_type:
        transactions = transactions.filter(transaction_type=transaction_type)
    
    paginator = Paginator(transactions, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'wallet/transaction_history.html', {'page_obj': page_obj})


@login_required
def transaction_detail_view(request, transaction_id):
    """
    View to display transaction details.
    """
    wallet = get_object_or_404(Wallet, user=request.user)
    transaction = get_object_or_404(Transaction, id=transaction_id, wallet=wallet)
    
    return render(request, 'wallet/transaction_detail.html', {'transaction': transaction})


@login_required
def withdrawal_request_view(request):
    """
    View to let verified users submit withdrawal requests.
    """
    if not request.user.is_verified:
        messages.error(request, 'Please verify your ID before requesting a withdrawal.')
        return redirect('identity_verification')

    wallet, created = Wallet.objects.get_or_create(user=request.user)

    if request.method == 'POST':
        form = WithdrawalRequestForm(request.POST, wallet=wallet)
        if form.is_valid():
            withdrawal = form.save(commit=False)
            withdrawal.wallet = wallet
            withdrawal.save()

            transaction = Transaction.objects.create(
                wallet=wallet,
                transaction_type=TransactionType.WITHDRAWAL,
                amount=withdrawal.amount,
                status=TransactionStatus.PENDING,
                reference_id=f'WDR-{withdrawal.id}',
                description=f'Withdrawal request via {withdrawal.get_method_display()}',
            )
            withdrawal.transaction = transaction
            withdrawal.save(update_fields=['transaction'])

            messages.success(request, 'Withdrawal request submitted successfully. It is now pending review.')
            return redirect('wallet_overview')
    else:
        form = WithdrawalRequestForm(wallet=wallet)

    recent_requests = WithdrawalRequest.objects.filter(wallet=wallet)[:5]
    context = {
        'form': form,
        'wallet': wallet,
        'recent_requests': recent_requests,
    }
    return render(request, 'wallet/withdrawal_request.html', context)
