
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.core.exceptions import ValidationError

User = get_user_model()

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
        }

class ProfileUpdateForm(forms.ModelForm):
    """Form for updating user profile information"""
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']
        widgets = {
            'first_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter your first name'
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter your last name'
            }),
            'email': forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter your email address'
            }),
        }

    def clean_email(self):
        email = self.cleaned_data['email']
        # Check if email is already taken by another user
        if User.objects.filter(email=email).exclude(pk=self.instance.pk).exists():
            raise ValidationError("This email address is already in use.")
        return email

class CustomPasswordResetForm(PasswordResetForm):
    """Custom password reset form with enhanced styling"""
    email = forms.EmailField(
        label="Email Address",
        max_length=254,
        widget=forms.EmailInput(attrs={
            'class': 'form-control with-icon',
            'placeholder': 'Enter your email address',
            'autocomplete': 'email'
        })
    )

    def clean_email(self):
        email = self.cleaned_data['email']
        if not User.objects.filter(email=email, is_active=True).exists():
            # Don't reveal whether the email exists for security
            pass
        return email

class CustomSetPasswordForm(SetPasswordForm):
    """Custom set password form with enhanced styling"""
    new_password1 = forms.CharField(
        label="New Password",
        widget=forms.PasswordInput(attrs={
            'class': 'form-control with-icon',
            'placeholder': 'Enter new password',
            'autocomplete': 'new-password'
        }),
        strip=False,
        help_text="Password must be at least 8 characters long."
    )
    new_password2 = forms.CharField(
        label="Confirm New Password",
        strip=False,
        widget=forms.PasswordInput(attrs={
            'class': 'form-control with-icon',
            'placeholder': 'Confirm new password',
            'autocomplete': 'new-password'
        })
    )



from django import forms
from django.contrib.auth.models import Group
from hr.models import Department
from .models import GroupPermissionManager, DepartmentPermissionAssignment

class DepartmentPermissionForm(forms.Form):
    """Form to manage permissions for a specific department"""
    department = forms.ModelChoiceField(
        queryset=Department.objects.filter(is_active=True),
        widget=forms.Select(attrs={'class': 'form-select'})
    )
    
    def __init__(self, *args, **kwargs):
        department = kwargs.pop('department', None)
        super().__init__(*args, **kwargs)
        
        if department:
            self.fields['department'].initial = department
            self.fields['department'].widget.attrs['readonly'] = True
        
        # Group permissions by category
        categories = GroupPermissionManager.PERMISSION_CATEGORIES
        assigned_permissions = set()
        
        if department:
            assigned_permissions = set(
                DepartmentPermissionAssignment.objects.filter(
                    department=department
                ).values_list('permission_id', flat=True)
            )
        
        for category_key, category_name in categories:
            permissions = GroupPermissionManager.objects.filter(
                category=category_key,
                is_active=True
            ).order_by('display_name')
            
            if permissions.exists():
                field_name = f'permissions_{category_key}'
                self.fields[field_name] = forms.ModelMultipleChoiceField(
                    queryset=permissions,
                    widget=forms.CheckboxSelectMultiple(attrs={
                        'class': 'form-check-input permission-checkbox',
                        'data-category': category_key
                    }),
                    required=False,
                    label=category_name,
                    initial=permissions.filter(id__in=assigned_permissions)
                )

class AddPermissionForm(forms.ModelForm):
    """Form to add new system permissions"""
    class Meta:
        model = GroupPermissionManager
        fields = ['name', 'display_name', 'description', 'category']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'e.g., view_customers, manage_billing'
            }),
            'display_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'e.g., View Customers, Manage Billing'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': 'Describe what this permission allows users to do'
            }),
            'category': forms.Select(attrs={'class': 'form-select'})
        }
    
    def clean_name(self):
        name = self.cleaned_data['name']
        # Ensure permission name follows convention
        if not name.islower() or ' ' in name:
            raise forms.ValidationError("Permission name must be lowercase with underscores (e.g., view_customers)")
        return name

