from django import forms
from django.contrib.auth import get_user_model
from .models import MpesaConfiguration

User = get_user_model()


class MpesaConfigurationForm(forms.ModelForm):
    """
    Form for M-Pesa configuration
    """
    
    class Meta:
        model = MpesaConfiguration
        fields = [
            'environment', 'consumer_key', 'consumer_secret', 
            'business_short_code', 'passkey', 'validation_url', 
            'confirmation_url', 'response_type'
        ]
        widgets = {
            'consumer_secret': forms.PasswordInput(render_value=True),
            'passkey': forms.PasswordInput(render_value=True),
            'validation_url': forms.URLInput(attrs={'placeholder': 'https://yourdomain.com/mpesa/validation/'}),
            'confirmation_url': forms.URLInput(attrs={'placeholder': 'https://yourdomain.com/mpesa/confirmation/'}),
        }
        help_texts = {
            'environment': 'Select sandbox for testing, production for live transactions',
            'consumer_key': 'Consumer key from M-Pesa developer portal',
            'consumer_secret': 'Consumer secret from M-Pesa developer portal',
            'business_short_code': 'Your M-Pesa paybill or till number',
            'passkey': 'Passkey for STK push (if applicable)',
            'validation_url': 'URL where M-Pesa will send validation requests',
            'confirmation_url': 'URL where M-Pesa will send confirmation requests',
            'response_type': 'What to do if validation URL is unreachable',
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # Add CSS classes
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
        
        # Make certain fields required
        self.fields['consumer_key'].required = True
        self.fields['consumer_secret'].required = True
        self.fields['business_short_code'].required = True
        self.fields['validation_url'].required = True
        self.fields['confirmation_url'].required = True


class PaymentSimulationForm(forms.Form):
    """
    Form for simulating M-Pesa payments in sandbox
    """
    phone_number = forms.CharField(
        max_length=15,
        help_text='Phone number in format 0712345678 or 254712345678',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '0712345678'
        })
    )
    
    amount = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=1,
        help_text='Amount to simulate payment for',
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': '1000.00',
            'step': '0.01'
        })
    )
    
    bill_ref_number = forms.CharField(
        max_length=50,
        required=False,
        help_text='Account number/reference (optional)',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'LOAN-000001'
        })
    )
    
    def clean_phone_number(self):
        phone = self.cleaned_data['phone_number']
        
        # Remove any spaces or special characters
        phone = ''.join(filter(str.isdigit, phone))
        
        # Validate format
        if phone.startswith('254') and len(phone) == 12:
            return phone
        elif phone.startswith('0') and len(phone) == 10:
            return '254' + phone[1:]
        elif len(phone) == 9:
            return '254' + phone
        else:
            raise forms.ValidationError('Invalid phone number format')


class TransactionFilterForm(forms.Form):
    """
    Form for filtering M-Pesa transactions
    """
    
    status = forms.ChoiceField(
        choices=[],  # Will be populated in __init__
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    phone_number = forms.CharField(
        max_length=20,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Search by phone number'
        })
    )
    
    amount_min = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        required=False,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'Min amount'
        })
    )
    
    amount_max = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        required=False,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'Max amount'
        })
    )
    
    date_from = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control',
            'type': 'date'
        })
    )
    
    date_to = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control',
            'type': 'date'
        })
    )
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # Populate status choices dynamically
        from .models import MpesaTransaction
        status_choices = [('', 'All Statuses')] + list(MpesaTransaction.STATUS_CHOICES)
        self.fields['status'].choices = status_choices


class ManualPaymentForm(forms.Form):
    """
    Form for manually processing payments
    """
    borrower = forms.ModelChoiceField(
        queryset=User.objects.filter(role='borrower'),
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text='Select the borrower who made the payment'
    )
    
    loan = forms.ModelChoiceField(
        queryset=None,  # Will be populated dynamically
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text='Select specific loan (optional - will auto-match if not selected)'
    )
    
    amount = forms.DecimalField(
        max_digits=12,
        decimal_places=2,
        min_value=1,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': '1000.00',
            'step': '0.01'
        })
    )
    
    mpesa_transaction_id = forms.CharField(
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'M-Pesa transaction ID'
        })
    )
    
    phone_number = forms.CharField(
        max_length=15,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '254712345678'
        })
    )
    
    notes = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 3,
            'placeholder': 'Additional notes about this payment'
        }),
        required=False
    )
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # If borrower is selected, filter loans
        if 'borrower' in self.data:
            try:
                borrower_id = int(self.data.get('borrower'))
                from loans.models import Loan
                self.fields['loan'].queryset = Loan.active_objects.filter(
                    borrower_id=borrower_id,
                    status='active'
                )
            except (ValueError, TypeError):
                self.fields['loan'].queryset = self.fields['loan'].queryset.none()
        else:
            from loans.models import Loan
            self.fields['loan'].queryset = Loan.objects.none()