from django import forms
from django.contrib.auth.forms import AuthenticationForm
from .models import CustomUser
from core.models import Branch


class CustomLoginForm(AuthenticationForm):
    username = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control gradient-input',
            'placeholder': 'Enter username',
            'autofocus': True
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control gradient-input',
            'placeholder': 'Enter password'
        })
    )


from django.contrib.auth.forms import UserCreationForm, UserChangeForm


class UserCreateForm(UserCreationForm):
    """
    Used for creating a new user with password1/password2.
    Superadmin role is not selectable.
    Pass company=<Company instance> to scope the branch queryset.
    """
    role = forms.ChoiceField(
        choices=[(value, label) for value, label in CustomUser.ROLE_CHOICES if value != "superadmin"],
        label="Role",
    )
    branch = forms.ModelChoiceField(
        queryset=Branch.objects.none(),  # overridden in __init__
        required=False,
        empty_label="-- Select branch (optional) --",
        label="Branch",
    )

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + (
            "first_name",
            "last_name",
            "email",
            "phone",
            "role",
            "branch",
            "is_active",
        )

    def __init__(self, *args, **kwargs):
        company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)
        
        # Make email mandatory for all staff creation
        if 'email' in self.fields:
            self.fields['email'].required = True
            
        if company:
            self.fields['branch'].queryset = Branch.objects.filter(company=company, is_active=True)
        else:
            self.fields['branch'].queryset = Branch.objects.none()


class UserUpdateForm(UserChangeForm):
    """
    Used for editing user – no password fields here.
    Superadmin role not selectable.
    Pass company=<Company instance> to scope the branch queryset.
    """
    password = None  # hide password field

    role = forms.ChoiceField(
        choices=[(value, label) for value, label in CustomUser.ROLE_CHOICES if value != "superadmin"],
        label="Role",
    )
    branch = forms.ModelChoiceField(
        queryset=Branch.objects.none(),  # overridden in __init__
        required=False,
        empty_label="-- Select branch (optional) --",
        label="Branch",
    )

    class Meta:
        model = CustomUser
        fields = [
            "username",
            "first_name",
            "last_name",
            "email",
            "phone",
            "role",
            "branch",
            "is_active",
        ]

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

        # Make email mandatory for all staff updates
        if 'email' in self.fields:
            self.fields['email'].required = True
            
        if company:
            self.fields['branch'].queryset = Branch.objects.filter(company=company, is_active=True)
        else:
            self.fields['branch'].queryset = Branch.objects.none()

