# -*- coding: utf-8 -*-
"""
Accounts Forms Module

This module contains form classes for the accounts app, providing
user-friendly interfaces for account management, user registration,
profile updates, and administrative operations.

Forms:
    - UserCreationForm: User registration
    - UserUpdateForm: Profile updates
    - UserAdminForm: Administrative user management
    - ProfileForm: User profile management
    - PasswordChangeForm: Password updates
    - BulkUserActionForm: Bulk operations

Features:
    - Form validation and error handling
    - Custom field widgets and styling
    - Integration with User model
    - Role and permission management
    - Bulk operations support
    - Security validations

Usage:
    from apps.accounts.forms import UserCreationForm, ProfileForm
    
    # User registration
    form = UserCreationForm(data=request.POST)
    if form.is_valid():
        user = form.save()
    
    # Profile update
    form = ProfileForm(instance=request.user, data=request.POST)
    if form.is_valid():
        form.save()

Security:
    - Password strength validation
    - Email verification
    - CSRF protection
    - Input sanitization
"""

from django import forms
from django.contrib.auth.forms import UserCreationForm as BaseUserCreationForm
from django.contrib.auth.forms import UserChangeForm as BaseUserChangeForm
from django.contrib.auth import authenticate
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.password_validation import validate_password

from .models import User


class UserCreationForm(BaseUserCreationForm):
    """
    Form for creating new user accounts.
    
    Extends Django's UserCreationForm with additional fields
    and custom validation for the User model.
    """
    
    email = forms.EmailField(
        required=True,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your email address...'),
            'autocomplete': 'email'
        }),
        help_text=_('Required. Enter a valid email address.')
    )
    
    first_name = forms.CharField(
        max_length=150,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your first name...'),
            'autocomplete': 'given-name'
        })
    )
    
    last_name = forms.CharField(
        max_length=150,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your last name...'),
            'autocomplete': 'family-name'
        })
    )
    
    password1 = forms.CharField(
        label=_('Password'),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter password...'),
            'autocomplete': 'new-password'
        }),
        help_text=_('Password must be at least 8 characters long.')
    )
    
    password2 = forms.CharField(
        label=_('Confirm Password'),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': _('Confirm password...'),
            'autocomplete': 'new-password'
        })
    )
    
    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'password1', 'password2')
    
    def clean_email(self):
        """Validate email uniqueness."""
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise ValidationError(_('A user with this email already exists.'))
        return email
    
    def clean_password1(self):
        """Validate password strength."""
        password1 = self.cleaned_data.get('password1')
        if password1:
            validate_password(password1)
        return password1
    
    def save(self, commit=True):
        """Save user with email as username."""
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        user.username = self.cleaned_data['email']
        if commit:
            user.save()
        return user


class UserUpdateForm(BaseUserChangeForm):
    """
    Form for updating user profiles.
    
    Allows users to update their profile information
    without changing sensitive fields like password.
    """
    
    password = None  # Remove password field
    
    email = forms.EmailField(
        required=True,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your email address...'),
            'readonly': True
        })
    )
    
    first_name = forms.CharField(
        max_length=150,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your first name...')
        })
    )
    
    last_name = forms.CharField(
        max_length=150,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your last name...')
        })
    )
    
    phone = forms.CharField(
        max_length=20,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your phone number...')
        })
    )
    
    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'phone')


class ProfileForm(forms.ModelForm):
    """
    Form for user profile management.
    
    Handles user profile updates including personal information
    and preferences.
    """
    
    class Meta:
        model = User
        fields = (
            'first_name', 'last_name', 'phone', 'bio',
            'timezone', 'language', 'avatar'
        )
        widgets = {
            'first_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('First name')
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Last name')
            }),
            'phone': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Phone number')
            }),
            'bio': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': _('Tell us about yourself...')
            }),
            'timezone': forms.Select(attrs={
                'class': 'form-control'
            }),
            'language': forms.Select(attrs={
                'class': 'form-control'
            }),
            'avatar': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            })
        }


class BulkUserActionForm(forms.Form):
    """
    Form for bulk user operations.
    
    Allows administrators to perform bulk actions
    on multiple users simultaneously.
    """
    
    ACTION_CHOICES = [
        ('activate', _('Activate Users')),
        ('deactivate', _('Deactivate Users')),
        ('delete', _('Delete Users')),
        ('export', _('Export Users')),
    ]
    
    action = forms.ChoiceField(
        choices=ACTION_CHOICES,
        widget=forms.Select(attrs={
            'class': 'form-control'
        })
    )
    
    user_ids = forms.CharField(
        widget=forms.HiddenInput()
    )
    
    def clean_user_ids(self):
        """Validate user IDs."""
        user_ids = self.cleaned_data.get('user_ids', '')
        try:
            ids = [int(id.strip()) for id in user_ids.split(',') if id.strip()]
            if not ids:
                raise ValidationError(_('No users selected.'))
            return ids
        except ValueError:
            raise ValidationError(_('Invalid user IDs.'))