
from django import forms
from django.forms import formset_factory
from .models import Expense, ExpenseAttachment, BudgetAllocation, ExpenseCategory
from hr.models import Employee
from datetime import date

class ExpenseForm(forms.ModelForm):
    class Meta:
        model = Expense
        fields = [
            'category', 'budget_allocation', 'title', 'description', 'amount', 
            'expense_date', 'vendor_name', 'vendor_contact', 'notes', 'is_reimbursable'
        ]
        widgets = {
            'category': forms.Select(attrs={'class': 'form-control'}),
            'budget_allocation': forms.Select(attrs={'class': 'form-control'}),
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Brief description'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': 'Detailed description'}),
            'amount': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01', 'min': '0'}),
            'expense_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'vendor_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Vendor/Supplier name'}),
            'vendor_contact': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone/Email'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'is_reimbursable': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }
    
    def __init__(self, *args, **kwargs):
        employee = kwargs.pop('employee', None)
        super().__init__(*args, **kwargs)
        
        if employee:
            # Filter budget allocations for the current employee
            self.fields['budget_allocation'].queryset = BudgetAllocation.objects.filter(
                employee=employee,
                is_active=True,
                start_date__lte=date.today(),
                end_date__gte=date.today()
            )
            
            # Update budget allocation choices to show remaining amounts
            choices = [('', '-- Select Budget Allocation (Optional) --')]
            for allocation in self.fields['budget_allocation'].queryset:
                choice_text = f"{allocation.category.name} - KSh {allocation.remaining_amount:.2f} remaining"
                choices.append((allocation.id, choice_text))
            self.fields['budget_allocation'].choices = choices

class ExpenseAttachmentForm(forms.ModelForm):
    class Meta:
        model = ExpenseAttachment
        fields = ['attachment_type', 'title', 'file']
        widgets = {
            'attachment_type': forms.Select(attrs={'class': 'form-control'}),
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Description of attachment'}),
            'file': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*,.pdf,.doc,.docx'}),
        }

# Create a formset for multiple attachments
ExpenseAttachmentFormSet = formset_factory(
    ExpenseAttachmentForm, 
    extra=3, 
    max_num=10, 
    can_delete=True
)

class BudgetAllocationForm(forms.ModelForm):
    class Meta:
        model = BudgetAllocation
        fields = [
            'employee', 'category', 'allocated_amount', 'allocation_period',
            'start_date', 'end_date', 'notes'
        ]
        widgets = {
            'employee': forms.Select(attrs={'class': 'form-control'}),
            'category': forms.Select(attrs={'class': 'form-control'}),
            'allocated_amount': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01', 'min': '0'}),
            'allocation_period': forms.Select(attrs={'class': 'form-control'}),
            'start_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'end_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
        }

class ExpenseApprovalForm(forms.Form):
    action = forms.ChoiceField(
        choices=[('approve', 'Approve'), ('reject', 'Reject')],
        widget=forms.RadioSelect(attrs={'class': 'form-check-input'})
    )
    comments = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Comments (optional)'})
    )
    rejection_reason = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Reason for rejection'})
    )

class ExpenseFilterForm(forms.Form):
    MONTH_CHOICES = [
        ('', 'All Months'),
        ('1', 'January'), ('2', 'February'), ('3', 'March'), ('4', 'April'),
        ('5', 'May'), ('6', 'June'), ('7', 'July'), ('8', 'August'),
        ('9', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December'),
    ]
    
    STATUS_CHOICES = [
        ('', 'All Status'),
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        ('paid', 'Paid'),
    ]
    
    employee = forms.ModelChoiceField(
        queryset=Employee.objects.filter(employment_status='active'),
        required=False,
        empty_label="All Employees",
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    category = forms.ModelChoiceField(
        queryset=ExpenseCategory.objects.filter(is_active=True),
        required=False,
        empty_label="All Categories",
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    status = forms.ChoiceField(
        choices=STATUS_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    month = forms.ChoiceField(
        choices=MONTH_CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    year = forms.ChoiceField(
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Populate year choices
        current_year = date.today().year
        year_choices = [('', 'All Years')]
        for year in range(current_year - 5, current_year + 2):
            year_choices.append((str(year), str(year)))
        self.fields['year'].choices = year_choices

class ExpenseCategoryForm(forms.ModelForm):
    class Meta:
        model = ExpenseCategory
        fields = ['name', 'description', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter category name'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': 'Enter category description'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].help_text = 'Enter a unique name for this expense category'
        self.fields['description'].help_text = 'Provide a detailed description of what expenses this category covers'
        self.fields['is_active'].help_text = 'Uncheck to hide this category from expense forms'
