"""
Forms for wallet app.
"""
from django import forms
from django.db.models import Sum
from .models import WithdrawalRequest


class WithdrawalRequestForm(forms.ModelForm):
    """
    Form for creating user withdrawal requests.
    """
    def __init__(self, *args, wallet=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.wallet = wallet

    class Meta:
        model = WithdrawalRequest
        fields = ('amount', 'method', 'destination_details', 'notes')
        widgets = {
            'amount': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01', 'min': '1'}),
            'method': forms.Select(attrs={'class': 'form-select'}),
            'destination_details': forms.TextInput(
                attrs={'class': 'form-control', 'placeholder': 'Wallet address or bank account details'}
            ),
            'notes': forms.Textarea(
                attrs={'class': 'form-control', 'rows': 4, 'placeholder': 'Optional note for admin'}
            ),
        }

    def clean_amount(self):
        amount = self.cleaned_data.get('amount')

        if amount is None or amount <= 0:
            raise forms.ValidationError('Please enter a valid withdrawal amount.')

        if self.wallet:
            pending_total = self.wallet.withdrawal_requests.filter(status='PENDING').aggregate(
                total=Sum('amount')
            )['total'] or 0
            available_for_withdrawal = self.wallet.balance - pending_total

            if amount > available_for_withdrawal:
                raise forms.ValidationError(
                    'Withdrawal amount exceeds your available balance after pending withdrawal requests.'
                )

        return amount
