from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
from .models import UserGroup

User = get_user_model()

class CustomUserCreationForm(UserCreationForm):
    """Form for creating new users"""
    
    class Meta(UserCreationForm.Meta):
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'user_type', 
                 'department', 'employee_id', 'phone')
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Make password fields required
        self.fields['password1'].required = True
        self.fields['password2'].required = True
        
        # Add Bootstrap classes
        for field in self.fields.values():
            field.widget.attrs.update({'class': 'form-control'})

class CustomUserForm(UserChangeForm):
    """Form for editing existing users"""
    
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'user_type', 
                 'department', 'employee_id', 'phone', 'is_active', 'groups')
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Remove password field from edit form
        if 'password' in self.fields:
            del self.fields['password']
        
        # Add Bootstrap classes
        for field in self.fields.values():
            if isinstance(field.widget, forms.CheckboxInput):
                field.widget.attrs.update({'class': 'form-check-input'})
            else:
                field.widget.attrs.update({'class': 'form-control'})

class UserGroupForm(forms.ModelForm):
    """Form for user groups"""
    
    class Meta:
        model = UserGroup
        fields = ('name', 'description', 'users', 'permissions')
        widgets = {
            'description': forms.Textarea(attrs={'rows': 3}),
            'permissions': forms.Textarea(attrs={'rows': 5, 'placeholder': 'Enter JSON permissions'}),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Add Bootstrap classes
        for field in self.fields.values():
            if isinstance(field.widget, forms.CheckboxSelectMultiple):
                field.widget.attrs.update({'class': 'form-check-input'})
            elif isinstance(field.widget, forms.SelectMultiple):
                field.widget.attrs.update({'class': 'form-select'})
            else:
                field.widget.attrs.update({'class': 'form-control'})
    
    def clean_permissions(self):
        """Validate permissions JSON field"""
        permissions = self.cleaned_data.get('permissions')
        if permissions:
            try:
                import json
                if isinstance(permissions, str):
                    json.loads(permissions)
                return permissions
            except json.JSONDecodeError:
                raise forms.ValidationError("Invalid JSON format for permissions")
        return permissions

class ProfileEditForm(forms.ModelForm):
    """Form for editing user profile"""
    
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'phone', 'department', 'profile_picture')
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Add Bootstrap classes
        for field in self.fields.values():
            if isinstance(field.widget, forms.FileInput):
                field.widget.attrs.update({'class': 'form-control'})
            else:
                field.widget.attrs.update({'class': 'form-control'})
