"""
Views for accounts app.
"""
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.views import PasswordChangeView, PasswordResetView, PasswordResetConfirmView
from django.urls import reverse_lazy
from .forms import (
    UserRegistrationForm,
    UserProfileForm,
    IdentityVerificationForm,
    CustomPasswordChangeForm,
)
from .models import User
from referrals.services import get_team_level_summary
from signals.services import get_user_signal_dashboard_data
from wallet.models import Wallet


def signup_view(request):
    """
    User registration view with referral code support.
    """
    if request.user.is_authenticated:
        return redirect('dashboard')
    
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            referral_code = form.cleaned_data.get('referrer_code')
            user = form.save(commit=False)
            
            # Handle referral
            if referral_code:
                referrer = User.objects.filter(referral_code=referral_code).first()
                if referrer:
                    user.referred_by = referrer
            
            user.save()
            
            # Create wallet for new user
            Wallet.objects.create(user=user)
            
            messages.success(request, 'Registration successful! Please login.')
            return redirect('login')
        else:
            # Show form errors
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f'{error}')
    else:
        # Check for referral code in URL
        initial_referral = request.GET.get('ref', '')
        form = UserRegistrationForm(initial={'referrer_code': initial_referral})
    
    return render(request, 'accounts/signup.html', {'form': form})


def login_view(request):
    """
    User login view.
    """
    if request.user.is_authenticated:
        return redirect('dashboard')
    
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            login(request, user)
            messages.success(request, f'Welcome back, {user.username}!')
            return redirect('dashboard')
        else:
            messages.error(request, 'Invalid username or password.')
    
    return render(request, 'accounts/login.html')


def logout_view(request):
    """
    User logout view.
    """
    logout(request)
    messages.info(request, 'You have been logged out.')
    return redirect('home')


@login_required
def dashboard_view(request):
    """
    User dashboard view showing overview of account.
    """
    user = request.user
    wallet = getattr(user, 'wallet', None)
    
    # Get recent activity
    from deposits.models import Deposit
    from signals.models import TradingSignal
    
    recent_deposits = Deposit.objects.filter(user=user)[:5]
    recent_signals = TradingSignal.objects.filter(status='ACTIVE')[:5]
    referrals = user.referred_users.all()[:5]
    team_summary = get_team_level_summary(user)
    automated_signal_dashboard = get_user_signal_dashboard_data(user)
    
    context = {
        'user': user,
        'wallet': wallet,
        'recent_deposits': recent_deposits,
        'recent_signals': recent_signals,
        'referrals': referrals,
        'total_referrals': user.get_total_referrals(),
        'referral_current_level': team_summary['current_level'],
        'referral_current_level_detail': team_summary['current_level_detail'],
        'referral_latest_team_bonus': team_summary['latest_team_bonus'],
        'automated_signal_dashboard': automated_signal_dashboard,
    }
    return render(request, 'accounts/dashboard.html', context)


@login_required
def profile_view(request):
    """
    User profile view.
    """
    user = request.user
    return render(request, 'accounts/profile.html', {'user': user})


@login_required
def edit_profile_view(request):
    """
    User profile edit view.
    """
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, 'Profile updated successfully!')
            return redirect('profile')
    else:
        form = UserProfileForm(instance=request.user)
    
    return render(request, 'accounts/edit_profile.html', {'form': form})


@login_required
def identity_verification_view(request):
    """
    View for uploading user identity verification documents.
    """
    if request.method == 'POST':
        form = IdentityVerificationForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            user = form.save(commit=False)

            # Any new document upload should go back to review state.
            if request.FILES.get('id_card_image') or request.FILES.get('selfie_image'):
                user.is_verified = False

            user.save()
            messages.success(request, 'Verification documents submitted successfully. Please wait for admin approval.')
            return redirect('identity_verification')
    else:
        form = IdentityVerificationForm(instance=request.user)

    return render(request, 'accounts/verification.html', {'form': form, 'user': request.user})


class CustomPasswordChangeView(PasswordChangeView):
    """
    Custom password change view with Bootstrap styling.
    """
    form_class = CustomPasswordChangeForm
    template_name = 'accounts/change_password.html'
    success_url = reverse_lazy('dashboard')
    
    def form_valid(self, form):
        messages.success(self.request, 'Password changed successfully!')
        return super().form_valid(form)


def password_reset_request(request):
    """
    Password reset request view.
    """
    return PasswordResetView.as_view(
        template_name='accounts/password_reset.html',
        email_template_name='accounts/password_reset_email.html',
        success_url=reverse_lazy('password_reset_done')
    )(request)


def password_reset_confirm(request, uidb64, token):
    """
    Password reset confirmation view.
    """
    return PasswordResetConfirmView.as_view(
        template_name='accounts/password_reset_confirm.html',
        success_url=reverse_lazy('password_reset_complete')
    )(request, uidb64=uidb64, token=token)
