"""
Views for deposits app.
"""
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.utils import timezone
from referrals.services import get_maximum_qualifying_deposit, get_minimum_qualifying_deposit
from .models import Deposit, PaymentInfo, DepositStatus
from .forms import DepositForm, PaymentInfoForm, DepositVerificationForm
from .services import apply_deposit_approval_effects, reverse_deposit_approval_effects


@login_required
def deposit_request_view(request):
    """
    View for users to submit deposit requests.
    """
    payment_info = PaymentInfo.objects.filter(is_active=True)
    
    if request.method == 'POST':
        form = DepositForm(request.POST, request.FILES)
        if form.is_valid():
            deposit = form.save(commit=False)
            deposit.user = request.user
            deposit.save()
            messages.success(request, 'Deposit request submitted successfully! We will review it shortly.')
            return redirect('deposit_history')
        for errors in form.errors.values():
            for error in errors:
                messages.error(request, error)
    else:
        form = DepositForm()
    
    return render(request, 'deposits/deposit_request.html', {
        'form': form,
        'payment_info': payment_info,
        'minimum_deposit': get_minimum_qualifying_deposit(),
        'maximum_deposit': get_maximum_qualifying_deposit(),
    })


@login_required
def deposit_history_view(request):
    """
    View for users to see their deposit history.
    """
    deposits = Deposit.objects.filter(user=request.user).order_by('-created_at')
    
    paginator = Paginator(deposits, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'deposits/deposit_history.html', {'page_obj': page_obj})


@login_required
def deposit_detail_view(request, deposit_id):
    """
    View for users to see deposit details.
    """
    deposit = get_object_or_404(Deposit, id=deposit_id, user=request.user)
    return render(request, 'deposits/deposit_detail.html', {'deposit': deposit})


# Admin views
@login_required
def admin_deposits_view(request):
    """
    Admin view to manage all deposits.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    deposits = Deposit.objects.all().order_by('-created_at')
    
    # Filter by status
    status = request.GET.get('status')
    if status:
        deposits = deposits.filter(status=status)
    
    # Filter by payment method
    method = request.GET.get('method')
    if method:
        deposits = deposits.filter(payment_method=method)
    
    paginator = Paginator(deposits, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'deposits/admin_deposits.html', {'page_obj': page_obj})


@login_required
def admin_deposit_verify(request, deposit_id):
    """
    Admin view to verify/approve a deposit.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    deposit = get_object_or_404(Deposit, id=deposit_id)
    
    if request.method == 'POST':
        old_status = deposit.status
        form = DepositVerificationForm(request.POST, instance=deposit)
        if form.is_valid():
            deposit = form.save(commit=False)
            deposit.verified_by = request.user
            deposit.verified_at = timezone.now()
            deposit.save()
            
            if deposit.status == DepositStatus.APPROVED and old_status != DepositStatus.APPROVED:
                apply_deposit_approval_effects(deposit)
            elif deposit.status != DepositStatus.APPROVED and old_status == DepositStatus.APPROVED:
                reverse_deposit_approval_effects(deposit)
            
            messages.success(request, f'Deposit #{deposit.id} {deposit.status.lower()} successfully!')
            return redirect('admin_deposits')
    else:
        form = DepositVerificationForm(instance=deposit)
    
    return render(request, 'deposits/admin_deposit_verify.html', {'form': form, 'deposit': deposit})


@login_required
def admin_payment_info_view(request):
    """
    Admin view to manage payment information.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    payment_info = PaymentInfo.objects.all()
    return render(request, 'deposits/admin_payment_info.html', {'payment_info': payment_info})


@login_required
def admin_payment_info_create(request):
    """
    Admin view to create payment information.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    if request.method == 'POST':
        form = PaymentInfoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, 'Payment information created successfully!')
            return redirect('admin_payment_info')
    else:
        form = PaymentInfoForm()
    
    return render(request, 'deposits/admin_payment_info_form.html', {'form': form, 'action': 'Create'})


@login_required
def admin_payment_info_edit(request, info_id):
    """
    Admin view to edit payment information.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    payment_info = get_object_or_404(PaymentInfo, id=info_id)
    
    if request.method == 'POST':
        form = PaymentInfoForm(request.POST, request.FILES, instance=payment_info)
        if form.is_valid():
            form.save()
            messages.success(request, 'Payment information updated successfully!')
            return redirect('admin_payment_info')
    else:
        form = PaymentInfoForm(instance=payment_info)
    
    return render(request, 'deposits/admin_payment_info_form.html', {'form': form, 'action': 'Edit'})
