from django import forms
from .models import Expense
from users.models import Branch
from loans.models import Loan


class ExpenseForm(forms.ModelForm):
    """Form for creating and editing expenses"""
    
    class Meta:
        model = Expense
        fields = [
            'title', 'description', 'category', 'amount', 'payment_method',
            'paid_to', 'branch', 'loan', 'expense_date', 'receipt_path',
            'reference_number', 'notes'
        ]
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'placeholder': 'Enter expense title'
            }),
            'description': forms.Textarea(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'rows': 3,
                'placeholder': 'Enter detailed description'
            }),
            'category': forms.Select(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
            }),
            'amount': forms.NumberInput(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'placeholder': '0.00',
                'step': '0.01',
                'min': '0.01'
            }),
            'payment_method': forms.Select(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
            }),
            'paid_to': forms.TextInput(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'placeholder': 'Recipient/Vendor name'
            }),
            'branch': forms.Select(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
            }),
            'loan': forms.Select(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
            }),
            'expense_date': forms.DateInput(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'type': 'date'
            }),
            'receipt_path': forms.FileInput(attrs={
                'class': 'mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-primary-dark',
                'accept': 'image/*,.pdf'
            }),
            'reference_number': forms.TextInput(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'placeholder': 'Transaction/Reference number'
            }),
            'notes': forms.Textarea(attrs={
                'class': 'mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
                'rows': 2,
                'placeholder': 'Additional notes'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # Make loan field optional
        self.fields['loan'].required = False
        self.fields['loan'].empty_label = "-- Not loan-related --"
        
        # Filter branches based on user access
        if user:
            if user.is_superuser:
                # Superusers can see all active branches
                self.fields['branch'].queryset = Branch.objects.filter(is_active=True)
            elif hasattr(user, 'accessible_branches') and user.accessible_branches.exists():
                # Users with accessible_branches can see those branches
                self.fields['branch'].queryset = user.accessible_branches.filter(is_active=True)
            elif user.branch:
                # Users with a single branch can only see their branch
                self.fields['branch'].queryset = Branch.objects.filter(id=user.branch.id, is_active=True)
            else:
                # Fallback: show all active branches
                self.fields['branch'].queryset = Branch.objects.filter(is_active=True)
            
            # Set default branch
            if user.branch and not self.instance.pk:
                self.fields['branch'].initial = user.branch
            
            # Filter loans by accessible branches
            if user.is_superuser:
                self.fields['loan'].queryset = Loan.objects.filter(
                    status='active'
                ).select_related('borrower')
            elif hasattr(user, 'accessible_branches') and user.accessible_branches.exists():
                branch_ids = user.accessible_branches.values_list('id', flat=True)
                self.fields['loan'].queryset = Loan.objects.filter(
                    borrower__branch_id__in=branch_ids,
                    status='active'
                ).select_related('borrower')
            elif user.branch:
                self.fields['loan'].queryset = Loan.objects.filter(
                    borrower__branch=user.branch,
                    status='active'
                ).select_related('borrower')
            else:
                # Fallback: show all active loans
                self.fields['loan'].queryset = Loan.objects.filter(
                    status='active'
                ).select_related('borrower')


class ExpenseFilterForm(forms.Form):
    """Form for filtering expenses"""
    
    search = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
            'placeholder': 'Search by title, paid to, or reference...'
        })
    )
    
    category = forms.ChoiceField(
        required=False,
        choices=[('', 'All Categories')] + Expense.CATEGORY_CHOICES,
        widget=forms.Select(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
        })
    )
    
    payment_method = forms.ChoiceField(
        required=False,
        choices=[('', 'All Payment Methods')] + Expense.PAYMENT_METHOD_CHOICES,
        widget=forms.Select(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
        })
    )
    
    status = forms.ChoiceField(
        required=False,
        choices=[('', 'All Statuses')] + Expense.STATUS_CHOICES,
        widget=forms.Select(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
        })
    )
    
    branch = forms.ModelChoiceField(
        required=False,
        queryset=Branch.objects.none(),  # Will be set in __init__
        empty_label='All Branches',
        widget=forms.Select(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
        })
    )
    
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # Set branch queryset based on user permissions
        if user:
            if user.is_superuser:
                self.fields['branch'].queryset = Branch.objects.filter(is_active=True)
            elif hasattr(user, 'accessible_branches') and user.accessible_branches.exists():
                self.fields['branch'].queryset = user.accessible_branches.filter(is_active=True)
            elif user.branch:
                self.fields['branch'].queryset = Branch.objects.filter(id=user.branch.id, is_active=True)
            else:
                self.fields['branch'].queryset = Branch.objects.filter(is_active=True)
        else:
            # Default to all active branches if no user provided
            self.fields['branch'].queryset = Branch.objects.filter(is_active=True)
    
    date_from = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
            'type': 'date'
        })
    )
    
    date_to = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
            'type': 'date'
        })
    )
    
    amount_min = forms.DecimalField(
        required=False,
        widget=forms.NumberInput(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
            'placeholder': 'Min amount',
            'step': '0.01'
        })
    )
    
    amount_max = forms.DecimalField(
        required=False,
        widget=forms.NumberInput(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm',
            'placeholder': 'Max amount',
            'step': '0.01'
        })
    )
    
    loan_related = forms.ChoiceField(
        required=False,
        choices=[('', 'All'), ('yes', 'Loan-Related Only'), ('no', 'Non-Loan Only')],
        widget=forms.Select(attrs={
            'class': 'block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm'
        })
    )
