"""
Views for referrals app.
"""
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from .models import ReferralEarning
from .services import (
    get_maximum_qualifying_deposit,
    get_minimum_qualifying_deposit,
    get_referred_user_bonus_percentage,
    get_referrer_bonus_percentage,
    get_team_level_summary,
)


@login_required
def referral_dashboard_view(request):
    """
    View to display user's referral dashboard.
    """
    user = request.user
    
    # Get all referral earnings
    earnings = ReferralEarning.objects.filter(user=user, is_credited=True)
    
    # Get direct referrals
    referrals = user.referred_users.all()
    
    # Calculate totals
    total_earned = sum(e.amount for e in earnings)
    total_referrals = referrals.count()
    team_summary = get_team_level_summary(user)
    
    context = {
        'user': user,
        'referral_link': request.build_absolute_uri(f'/signup/?ref={user.referral_code}'),
        'referrals': referrals,
        'earnings': earnings[:10],
        'total_earned': total_earned,
        'total_referrals': total_referrals,
        'qualified_team_members': team_summary['qualified_count'],
        'current_level': team_summary['current_level'],
        'current_level_detail': team_summary['current_level_detail'],
        'next_level': team_summary['next_level'],
        'team_levels': team_summary['levels'],
        'level_progress_percent': team_summary['progress_percent'],
        'latest_team_bonus': team_summary['latest_team_bonus'],
        'minimum_deposit': get_minimum_qualifying_deposit(),
        'maximum_deposit': get_maximum_qualifying_deposit(),
        'referrer_bonus_percentage': get_referrer_bonus_percentage(),
        'referred_user_bonus_percentage': get_referred_user_bonus_percentage(),
    }
    return render(request, 'referrals/referral_dashboard.html', context)


@login_required
def referral_history_view(request):
    """
    View to display user's referral history.
    """
    user = request.user
    earnings = ReferralEarning.objects.filter(user=user, is_credited=True).order_by('-created_at')
    
    paginator = Paginator(earnings, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'referrals/referral_history.html', {'page_obj': page_obj})


@login_required
def referral_network_view(request):
    """
    View to display user's referral network.
    """
    user = request.user
    referrals = user.referred_users.all()
    
    # Get referral levels (simple - just direct referrals for now)
    paginator = Paginator(referrals, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'referrals/referral_network.html', {'page_obj': page_obj})
