from django import forms
from django.forms import inlineformset_factory
from .models import WorkLog, Project, Worker, Team, ExpenseReceipt, ExpenseLineItem


# === WORK LOG FORM ===
class WorkLogForm(forms.ModelForm):
    end_date = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
        label="End Date (Optional)"
    )
    include_saturday = forms.BooleanField(
        required=False,
        label="Include Saturday",
        initial=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )
    include_sunday = forms.BooleanField(
        required=False,
        label="Include Sunday",
        initial=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )
    team = forms.ModelChoiceField(queryset=Team.objects.none(), required=False, empty_label="Select Team", widget=forms.Select(attrs={'class': 'form-control'}))

    overtime = forms.ChoiceField(
        choices=WorkLog.OT_CHOICES,
        required=False,
        initial=0,
        widget=forms.Select(attrs={'class': 'form-control'})
    )

    class Meta:
        model = WorkLog
        fields = ['date', 'project', 'workers', 'notes', 'overtime']
        widgets = {
            'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'project': forms.Select(attrs={'class': 'form-control'}),
            'workers': forms.CheckboxSelectMultiple(),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
        }

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

        projects_qs = Project.objects.filter(is_active=True)
        workers_qs = Worker.objects.filter(is_active=True)
        teams_qs = Team.objects.filter(is_active=True)

        if user and not user.is_superuser:
            self.fields['project'].queryset = projects_qs.filter(supervisors=user)

            managed_teams = user.managed_teams.all()
            worker_ids = managed_teams.values_list('workers__id', flat=True).distinct()
            self.fields['workers'].queryset = workers_qs.filter(id__in=worker_ids)

            self.fields['team'].queryset = teams_qs.filter(supervisor=user)
        else:
            self.fields['project'].queryset = projects_qs
            self.fields['workers'].queryset = workers_qs
            self.fields['team'].queryset = teams_qs


# === EXPENSE RECEIPT FORM ===
class ExpenseReceiptForm(forms.ModelForm):
    class Meta:
        model = ExpenseReceipt
        fields = ['date', 'vendor', 'description', 'payment_method', 'vat_type']
        widgets = {
            'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'vendor': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Vendor Name'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'payment_method': forms.Select(attrs={'class': 'form-control'}),
            'vat_type': forms.RadioSelect(attrs={'class': 'form-check-input'}),
        }


# === EXPENSE LINE ITEM FORMSET ===
ExpenseLineItemFormSet = inlineformset_factory(
    ExpenseReceipt, ExpenseLineItem,
    fields=['product', 'amount'],
    extra=1,
    can_delete=True,
    widgets={
        'product': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Item Name'}),
        'amount': forms.NumberInput(attrs={'class': 'form-control item-amount', 'step': '0.01'}),
    }
)
