from django import forms
from .models import WorkLog, Project, Worker, Team

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'}))

    class Meta:
        model = WorkLog
        fields = ['date', 'project', 'workers', 'notes']
        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)
        
        # Base querysets with active filter
        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:
            # Filter projects and workers based on user assignment
            self.fields['project'].queryset = projects_qs.filter(supervisors=user)
            
            # For workers, we might want to show workers from teams supervised by the user
            # OR just all active workers if that's the business rule. 
            # The previous code filtered workers by managed teams. Let's keep that logic but respecting is_active.
            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)
            
            # Filter teams
            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