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

This module contains forms for user management, registration, profile updates,
role assignment, and other account-related functionality.

Author: Senior Django Developer
Date: 2024
"""

from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.password_validation import validate_password
from django.core.validators import RegexValidator
from django.utils.html import strip_tags
import re

from .models import Role, User, Profile
from apps.authentication.utils import is_password_strong

# Get the custom user model
User = get_user_model()


class UserRegistrationForm(UserCreationForm):
    """
    Enhanced user registration form with additional fields and validation.
    
    Features:
    - Email validation
    - Password strength checking
    - Terms acceptance
    - Phone number validation
    - First and last name requirements
    """
    
    # Additional fields
    email = forms.EmailField(
        label=_('Email Address'),
        max_length=254,
        required=True,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your email address'),
            'autocomplete': 'email'
        }),
        help_text=_('We will send a verification email to this address.')
    )
    
    first_name = forms.CharField(
        label=_('First Name'),
        max_length=30,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your first name'),
            'autocomplete': 'given-name'
        })
    )
    
    last_name = forms.CharField(
        label=_('Last Name'),
        max_length=30,
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your last name'),
            'autocomplete': 'family-name'
        })
    )
    
    phone_number = forms.CharField(
        label=_('Phone Number'),
        max_length=20,
        required=False,
        validators=[
            RegexValidator(
                regex=r'^\+?1?\d{9,15}$',
                message=_('Phone number must be entered in the format: "+999999999". Up to 15 digits allowed.')
            )
        ],
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your phone number'),
            'autocomplete': 'tel'
        })
    )
    
    terms_accepted = forms.BooleanField(
        label=_('I accept the Terms of Service and Privacy Policy'),
        required=True,
        widget=forms.CheckboxInput(attrs={
            'class': 'form-check-input'
        }),
        error_messages={
            'required': _('You must accept the terms and conditions to register.')
        }
    )
    
    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'phone_number', 'password1', 'password2')
    
    def __init__(self, *args, **kwargs):
        """
        Initialize the form with custom styling and attributes.
        
        Args:
            *args: Variable length argument list
            **kwargs: Arbitrary keyword arguments
        """
        super().__init__(*args, **kwargs)
        
        # Customize password fields
        self.fields['password1'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': _('Enter a strong password'),
            'autocomplete': 'new-password'
        })
        
        self.fields['password2'].widget.attrs.update({
            'class': 'form-control',
            'placeholder': _('Confirm your password'),
            'autocomplete': 'new-password'
        })
        
        # Update help texts
        self.fields['password1'].help_text = _(
            'Your password must contain at least 8 characters, including uppercase, '
            'lowercase, numbers, and special characters.'
        )
    
    def clean_email(self):
        """
        Validate email uniqueness and format.
        
        Returns:
            str: Cleaned email address
            
        Raises:
            ValidationError: If email is invalid or already exists
        """
        email = self.cleaned_data.get('email')
        
        if email:
            # Convert to lowercase for consistency
            email = email.lower().strip()
            
            # Check if email already exists
            if User.objects.filter(email=email).exists():
                raise ValidationError(
                    _('A user with this email address already exists.')
                )
            
            # Additional email format validation
            if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
                raise ValidationError(
                    _('Please enter a valid email address.')
                )
        
        return email
    
    def clean_first_name(self):
        """
        Validate and clean first name.
        
        Returns:
            str: Cleaned first name
        """
        first_name = self.cleaned_data.get('first_name')
        
        if first_name:
            # Remove extra whitespace and capitalize
            first_name = ' '.join(first_name.split()).title()
            
            # Check for valid characters (letters, spaces, hyphens, apostrophes)
            if not re.match(r"^[a-zA-Z\s\-']+$", first_name):
                raise ValidationError(
                    _('First name can only contain letters, spaces, hyphens, and apostrophes.')
                )
        
        return first_name
    
    def clean_last_name(self):
        """
        Validate and clean last name.
        
        Returns:
            str: Cleaned last name
        """
        last_name = self.cleaned_data.get('last_name')
        
        if last_name:
            # Remove extra whitespace and capitalize
            last_name = ' '.join(last_name.split()).title()
            
            # Check for valid characters (letters, spaces, hyphens, apostrophes)
            if not re.match(r"^[a-zA-Z\s\-']+$", last_name):
                raise ValidationError(
                    _('Last name can only contain letters, spaces, hyphens, and apostrophes.')
                )
        
        return last_name
    
    def clean_password1(self):
        """
        Validate password strength.
        
        Returns:
            str: Cleaned password
            
        Raises:
            ValidationError: If password is not strong enough
        """
        password1 = self.cleaned_data.get('password1')
        
        if password1:
            # Use Django's built-in password validation
            validate_password(password1)
            
            # Additional custom password strength check
            if not is_password_strong(password1):
                raise ValidationError(
                    _('Password must contain at least 8 characters with uppercase, '
                      'lowercase, numbers, and special characters.')
                )
        
        return password1
    
    def save(self, commit=True):
        """
        Save the user instance with additional profile data.
        
        Args:
            commit: Whether to save to database
            
        Returns:
            User: Created user instance
        """
        user = super().save(commit=False)
        
        # Set email as username
        user.username = self.cleaned_data['email']
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        
        if commit:
            user.save()
            
            # Update or create user profile with phone number
            profile, created = Profile.objects.get_or_create(
                user=user,
                defaults={
                    'phone_number': self.cleaned_data.get('phone_number', '')
                }
            )
            
            if not created and self.cleaned_data.get('phone_number'):
                profile.phone_number = self.cleaned_data['phone_number']
                profile.save()
        
        return user


class UserUpdateForm(forms.ModelForm):
    """
    Form for updating user basic information.
    
    Allows users to update their email, first name, and last name.
    """
    
    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name')
        widgets = {
            'email': forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': _('Enter your email address')
            }),
            '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')
            })
        }
    
    def clean_email(self):
        """
        Validate email uniqueness (excluding current user).
        
        Returns:
            str: Cleaned email address
        """
        email = self.cleaned_data.get('email')
        
        if email:
            email = email.lower().strip()
            
            # Check if email exists for other users
            existing_user = User.objects.filter(email=email).exclude(pk=self.instance.pk)
            if existing_user.exists():
                raise ValidationError(
                    _('A user with this email address already exists.')
                )
        
        return email


class ProfileForm(forms.ModelForm):
    """
    Form for updating user profile information.
    
    Handles profile-specific fields like bio, birth date, avatar, etc.
    """
    
    class Meta:
        model = Profile
        fields = ('bio', 'birth_date', 'avatar', 'website', 'is_profile_public', 'email_notifications', 'sms_notifications')
        widgets = {
            'bio': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': _('Tell us about yourself')
            }),
            'birth_date': forms.DateInput(attrs={
                'class': 'form-control',
                'type': 'date'
            }), 
            'website': forms.URLInput(attrs={
                'class': 'form-control',
                'placeholder': _('Enter your website URL')
            }), 
            'avatar': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            })
        }
    
    def clean_bio(self):
        """
        Clean and validate bio field.
        
        Returns:
            str: Cleaned bio text
        """
        bio = self.cleaned_data.get('bio')
        
        if bio:
            # Strip HTML tags for security
            bio = strip_tags(bio).strip()
            
            # Limit bio length
            if len(bio) > 500:
                raise ValidationError(
                    _('Bio must be 500 characters or less.')
                )
        
        return bio
    
    def clean_avatar(self):
        """
        Validate avatar image file.
        
        Returns:
            File: Cleaned avatar file
        """
        avatar = self.cleaned_data.get('avatar')
        
        if avatar:
            # Check file size (max 5MB)
            if avatar.size > 5 * 1024 * 1024:
                raise ValidationError(
                    _('Avatar image must be smaller than 5MB.')
                )
            
            # Check file type
            allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
            if avatar.content_type not in allowed_types:
                raise ValidationError(
                    _('Avatar must be a JPEG, PNG, GIF, or WebP image.')
                )
        
        return avatar


class RoleForm(forms.ModelForm):
    """
    Form for creating and editing roles.
    
    Allows administrators to manage role information and permissions.
    """
    
    class Meta:
        model = Role
        fields = ('name', 'description', 'permissions')
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Enter role name')
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': _('Describe this role')
            }),
            'permissions': forms.CheckboxSelectMultiple(attrs={
                'class': 'form-check-input'
            })
        }
    
    def clean_name(self):
        """
        Validate role name uniqueness and format.
        
        Returns:
            str: Cleaned role name
        """
        name = self.cleaned_data.get('name')
        
        if name:
            # Clean and format name
            name = name.strip().title()
            
            # Check uniqueness (excluding current instance if editing)
            existing_role = Role.objects.filter(name=name)
            if self.instance.pk:
                existing_role = existing_role.exclude(pk=self.instance.pk)
            
            if existing_role.exists():
                raise ValidationError(
                    _('A role with this name already exists.')
                )
            
            # Validate name format
            if not re.match(r'^[a-zA-Z\s]+$', name):
                raise ValidationError(
                    _('Role name can only contain letters and spaces.')
                )
        
        return name


class UserRoleAssignmentForm(forms.Form):
    """
    Form for assigning roles to users.
    
    Allows administrators to select multiple roles for a user.
    """
    
    roles = forms.ModelMultipleChoiceField(
        queryset=Role.objects.all(),
        widget=forms.CheckboxSelectMultiple(attrs={
            'class': 'form-check-input'
        }),
        required=False,
        label=_('Assign Roles'),
        help_text=_('Select the roles to assign to this user.')
    )
    
    def __init__(self, *args, **kwargs):
        """
        Initialize form with user instance.
        
        Args:
            *args: Variable length argument list
            **kwargs: Arbitrary keyword arguments including 'user'
        """
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # Set initial values if user is provided
        if self.user:
            self.fields['roles'].initial = self.user.roles.all()


class UserSearchForm(forms.Form):
    """
    Form for searching and filtering users.
    
    Provides search functionality for the user list view.
    """
    
    search = forms.CharField(
        max_length=100,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Search by name, email, or phone'),
            'autocomplete': 'off'
        })
    )
    
    role = forms.ModelChoiceField(
        queryset=Role.objects.all(),
        required=False,
        empty_label=_('All Roles'),
        widget=forms.Select(attrs={
            'class': 'form-control'
        })
    )
    
    status = forms.ChoiceField(
        choices=[
            ('', _('All Users')),
            ('active', _('Active Users')),
            ('inactive', _('Inactive Users')),
            ('verified', _('Verified Users')),
            ('unverified', _('Unverified Users'))
        ],
        required=False,
        widget=forms.Select(attrs={
            'class': 'form-control'
        })
    )
    
    order_by = forms.ChoiceField(
        choices=[
            ('-date_joined', _('Newest First')),
            ('date_joined', _('Oldest First')),
            ('email', _('Email A-Z')),
            ('-email', _('Email Z-A')),
            ('first_name', _('First Name A-Z')),
            ('-first_name', _('First Name Z-A')),
            ('last_name', _('Last Name A-Z')),
            ('-last_name', _('Last Name Z-A')),
            ('-last_login', _('Last Login')),
        ],
        required=False,
        initial='-date_joined',
        widget=forms.Select(attrs={
            'class': 'form-control'
        })
    )


class BulkUserActionForm(forms.Form):
    """
    Form for performing bulk actions on users.
    
    Allows administrators to perform actions on multiple users at once.
    """
    
    ACTION_CHOICES = [
        ('activate', _('Activate Selected Users')),
        ('deactivate', _('Deactivate Selected Users')),
        ('delete', _('Delete Selected Users')),
        ('export', _('Export Selected Users'))
    ]
    
    action = forms.ChoiceField(
        choices=ACTION_CHOICES,
        widget=forms.Select(attrs={
            'class': 'form-control'
        }),
        label=_('Action')
    )
    
    selected_users = forms.ModelMultipleChoiceField(
        queryset=User.objects.all(),
        widget=forms.CheckboxSelectMultiple(),
        label=_('Selected Users')
    )
    
    confirm = forms.BooleanField(
        required=True,
        label=_('I confirm this action'),
        widget=forms.CheckboxInput(attrs={
            'class': 'form-check-input'
        })
    )


class PasswordChangeForm(forms.Form):
    """
    Custom password change form with enhanced validation.
    
    Provides secure password changing functionality.
    """
    
    current_password = forms.CharField(
        label=_('Current Password'),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your current password')
        })
    )
    
    new_password1 = forms.CharField(
        label=_('New Password'),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': _('Enter your new password')
        })
    )
    
    new_password2 = forms.CharField(
        label=_('Confirm New Password'),
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': _('Confirm your new password')
        })
    )
    
    def __init__(self, user, *args, **kwargs):
        """
        Initialize form with user instance.
        
        Args:
            user: User instance
            *args: Variable length argument list
            **kwargs: Arbitrary keyword arguments
        """
        self.user = user
        super().__init__(*args, **kwargs)
    
    def clean_current_password(self):
        """
        Validate current password.
        
        Returns:
            str: Current password
            
        Raises:
            ValidationError: If current password is incorrect
        """
        current_password = self.cleaned_data.get('current_password')
        
        if current_password and not self.user.check_password(current_password):
            raise ValidationError(_('Current password is incorrect.'))
        
        return current_password
    
    def clean_new_password1(self):
        """
        Validate new password strength.
        
        Returns:
            str: New password
        """
        new_password1 = self.cleaned_data.get('new_password1')
        
        if new_password1:
            validate_password(new_password1, self.user)
            
            if not is_password_strong(new_password1):
                raise ValidationError(
                    _('Password must contain at least 8 characters with uppercase, '
                      'lowercase, numbers, and special characters.')
                )
        
        return new_password1
    
    def clean(self):
        """
        Validate password confirmation.
        
        Returns:
            dict: Cleaned data
        """
        cleaned_data = super().clean()
        new_password1 = cleaned_data.get('new_password1')
        new_password2 = cleaned_data.get('new_password2')
        
        if new_password1 and new_password2:
            if new_password1 != new_password2:
                raise ValidationError(_('The two password fields must match.'))
        
        return cleaned_data
    
    def save(self):
        """
        Save the new password.
        
        Returns:
            User: Updated user instance
        """
        password = self.cleaned_data['new_password1']
        self.user.set_password(password)
        self.user.save()
        return self.user



# """Accounts Forms

# This module contains Django forms for user authentication, registration,
# and profile management in the accounts app.
# """

# from django import forms
# from django.contrib.auth.forms import (
#     UserCreationForm, AuthenticationForm, PasswordChangeForm
# )
# 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 apps.accounts.models import User, UserProfile


# class CustomAuthenticationForm(AuthenticationForm):
#     """Custom authentication form with email login."""
    
#     username = forms.EmailField(
#         label=_('Email'),
#         widget=forms.EmailInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your email'),
#             'autofocus': True,
#         })
#     )
    
#     password = forms.CharField(
#         label=_('Password'),
#         strip=False,
#         widget=forms.PasswordInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your password'),
#         })
#     )
    
#     remember_me = forms.BooleanField(
#         label=_('Remember me'),
#         required=False,
#         widget=forms.CheckboxInput(attrs={
#             'class': 'form-check-input',
#         })
#     )
    
#     error_messages = {
#         'invalid_login': _(
#             'Please enter a correct email and password. Note that both '
#             'fields may be case-sensitive.'
#         ),
#         'inactive': _('This account is inactive.'),
#     }
    
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         # Remove username field help text
#         self.fields['username'].help_text = None
    
#     def clean(self):
#         username = self.cleaned_data.get('username')
#         password = self.cleaned_data.get('password')
        
#         if username is not None and password:
#             self.user_cache = authenticate(
#                 self.request,
#                 username=username,
#                 password=password
#             )
#             if self.user_cache is None:
#                 raise self.get_invalid_login_error()
#             else:
#                 self.confirm_login_allowed(self.user_cache)
        
#         return self.cleaned_data


# class UserRegistrationForm(UserCreationForm):
#     """User registration form."""
    
#     email = forms.EmailField(
#         label=_('Email'),
#         required=True,
#         widget=forms.EmailInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your email'),
#         })
#     )
    
#     first_name = forms.CharField(
#         label=_('First Name'),
#         max_length=150,
#         required=True,
#         widget=forms.TextInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your first name'),
#         })
#     )
    
#     last_name = forms.CharField(
#         label=_('Last Name'),
#         max_length=150,
#         required=True,
#         widget=forms.TextInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your last name'),
#         })
#     )
    
#     username = forms.CharField(
#         label=_('Username'),
#         max_length=150,
#         required=True,
#         widget=forms.TextInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Choose a username'),
#         })
#     )
    
#     password1 = forms.CharField(
#         label=_('Password'),
#         strip=False,
#         widget=forms.PasswordInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter a strong password'),
#         }),
#         help_text=_(
#             'Your password must contain at least 8 characters and '
#             'cannot be entirely numeric.'
#         )
#     )
    
#     password2 = forms.CharField(
#         label=_('Confirm Password'),
#         strip=False,
#         widget=forms.PasswordInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Confirm your password'),
#         })
#     )
    
#     terms_accepted = forms.BooleanField(
#         label=_('I accept the Terms of Service and Privacy Policy'),
#         required=True,
#         widget=forms.CheckboxInput(attrs={
#             'class': 'form-check-input',
#         })
#     )
    
#     class Meta:
#         model = User
#         fields = (
#             'username', 'email', 'first_name', 'last_name',
#             'password1', 'password2'
#         )
    
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         # Remove help text for username
#         self.fields['username'].help_text = None
    
#     def clean_email(self):
#         """Validate email uniqueness."""
#         email = self.cleaned_data.get('email')
#         if email:
#             email = email.lower()
#             if User.objects.filter(email=email).exists():
#                 raise ValidationError(
#                     _('A user with this email already exists.')
#                 )
#         return email
    
#     def clean_username(self):
#         """Validate username uniqueness."""
#         username = self.cleaned_data.get('username')
#         if username:
#             if User.objects.filter(username=username).exists():
#                 raise ValidationError(
#                     _('A user with this username already exists.')
#                 )
#         return username
    
#     def save(self, commit=True):
#         """Save the user with lowercase email."""
#         user = super().save(commit=False)
#         user.email = self.cleaned_data['email'].lower()
#         if commit:
#             user.save()
#         return user


# class UserProfileForm(forms.ModelForm):
#     """User profile editing form."""
    
#     class Meta:
#         model = User
#         fields = [
#             'first_name', 'last_name', 'email', 'phone_number',
#             'bio', 'timezone_field', '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'),
#             }),
#             'email': forms.EmailInput(attrs={
#                 'class': 'form-control',
#                 'placeholder': _('Email Address'),
#             }),
#             'phone_number': forms.TextInput(attrs={
#                 'class': 'form-control',
#                 'placeholder': _('Phone Number'),
#             }),
#             'bio': forms.Textarea(attrs={
#                 'class': 'form-control',
#                 'rows': 4,
#                 'placeholder': _('Tell us about yourself...'),
#             }),
#             'timezone_field': forms.Select(attrs={
#                 'class': 'form-select',
#             }),
#             'language': forms.Select(attrs={
#                 'class': 'form-select',
#             }),
#             'avatar': forms.FileInput(attrs={
#                 'class': 'form-control',
#                 'accept': 'image/*',
#             }),
#         }
    
#     def clean_email(self):
#         """Validate email uniqueness (excluding current user)."""
#         email = self.cleaned_data.get('email')
#         if email:
#             email = email.lower()
#             queryset = User.objects.filter(email=email)
#             if self.instance and self.instance.pk:
#                 queryset = queryset.exclude(pk=self.instance.pk)
#             if queryset.exists():
#                 raise ValidationError(
#                     _('A user with this email already exists.')
#                 )
#         return email


# class UserProfileExtendedForm(forms.ModelForm):
#     """Extended user profile form including UserProfile fields."""
    
#     # User fields
#     first_name = forms.CharField(
#         label=_('First Name'),
#         max_length=150,
#         widget=forms.TextInput(attrs={'class': 'form-control'})
#     )
#     last_name = forms.CharField(
#         label=_('Last Name'),
#         max_length=150,
#         widget=forms.TextInput(attrs={'class': 'form-control'})
#     )
#     email = forms.EmailField(
#         label=_('Email'),
#         widget=forms.EmailInput(attrs={'class': 'form-control'})
#     )
#     phone_number = forms.CharField(
#         label=_('Phone Number'),
#         required=False,
#         widget=forms.TextInput(attrs={'class': 'form-control'})
#     )
#     bio = forms.CharField(
#         label=_('Biography'),
#         required=False,
#         widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 4})
#     )
    
#     class Meta:
#         model = UserProfile
#         fields = [
#             'job_title', 'company', 'department', 'website',
#             'address_line1', 'address_line2', 'city', 'state',
#             'postal_code', 'country'
#         ]
#         widgets = {
#             'job_title': forms.TextInput(attrs={'class': 'form-control'}),
#             'company': forms.TextInput(attrs={'class': 'form-control'}),
#             'department': forms.TextInput(attrs={'class': 'form-control'}),
#             'website': forms.URLInput(attrs={'class': 'form-control'}),
#             'address_line1': forms.TextInput(attrs={'class': 'form-control'}),
#             'address_line2': forms.TextInput(attrs={'class': 'form-control'}),
#             'city': forms.TextInput(attrs={'class': 'form-control'}),
#             'state': forms.TextInput(attrs={'class': 'form-control'}),
#             'postal_code': forms.TextInput(attrs={'class': 'form-control'}),
#             'country': forms.TextInput(attrs={'class': 'form-control'}),
#         }
    
#     def __init__(self, *args, **kwargs):
#         self.user = kwargs.pop('user', None)
#         super().__init__(*args, **kwargs)
        
#         if self.user:
#             # Populate user fields
#             self.fields['first_name'].initial = self.user.first_name
#             self.fields['last_name'].initial = self.user.last_name
#             self.fields['email'].initial = self.user.email
#             self.fields['phone_number'].initial = self.user.phone_number
#             self.fields['bio'].initial = self.user.bio
    
#     def save(self, commit=True):
#         """Save both user and profile data."""
#         profile = super().save(commit=False)
        
#         if self.user:
#             # Update user fields
#             self.user.first_name = self.cleaned_data['first_name']
#             self.user.last_name = self.cleaned_data['last_name']
#             self.user.email = self.cleaned_data['email'].lower()
#             self.user.phone_number = self.cleaned_data['phone_number']
#             self.user.bio = self.cleaned_data['bio']
            
#             if commit:
#                 self.user.save()
#                 profile.save()
        
#         return profile


# class CustomPasswordChangeForm(PasswordChangeForm):
#     """Custom password change form with better styling."""
    
#     old_password = forms.CharField(
#         label=_('Current Password'),
#         strip=False,
#         widget=forms.PasswordInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your current password'),
#             'autofocus': True,
#         })
#     )
    
#     new_password1 = forms.CharField(
#         label=_('New Password'),
#         strip=False,
#         widget=forms.PasswordInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Enter your new password'),
#         }),
#         help_text=_(
#             'Your password must contain at least 8 characters and '
#             'cannot be entirely numeric.'
#         )
#     )
    
#     new_password2 = forms.CharField(
#         label=_('Confirm New Password'),
#         strip=False,
#         widget=forms.PasswordInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Confirm your new password'),
#         })
#     )


# class ContactForm(forms.Form):
#     """Contact form for user inquiries."""
    
#     name = forms.CharField(
#         label=_('Name'),
#         max_length=100,
#         widget=forms.TextInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Your Name'),
#         })
#     )
    
#     email = forms.EmailField(
#         label=_('Email'),
#         widget=forms.EmailInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Your Email'),
#         })
#     )
    
#     subject = forms.CharField(
#         label=_('Subject'),
#         max_length=200,
#         widget=forms.TextInput(attrs={
#             'class': 'form-control',
#             'placeholder': _('Subject'),
#         })
#     )
    
#     message = forms.CharField(
#         label=_('Message'),
#         widget=forms.Textarea(attrs={
#             'class': 'form-control',
#             'rows': 6,
#             'placeholder': _('Your Message'),
#         })
#     )
    
#     def send_email(self):
#         """Send the contact form email."""
#         # Implementation for sending email
#         pass