from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.core.exceptions import ValidationError
from .models import Person, Referral, ContactMessage


class CustomAuthenticationForm(AuthenticationForm):
    """Custom login form with styled fields"""
    username = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'Email address',
            'autocomplete': 'email',
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'Password',
            'autocomplete': 'current-password',
        })
    )


class PersonRegistrationForm(UserCreationForm):
    """Registration form for new users"""
    
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'Email address',
        })
    )
    first_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'First name',
        })
    )
    last_name = forms.CharField(
        max_length=100,
        widget=forms.TextInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'Last name',
        })
    )
    role = forms.ChoiceField(
        choices=[('worker', 'Worker (Advertise services)'), ('client', 'Client (Find companions)')],
        widget=forms.Select(attrs={
            'class': 'form-select bg-dark text-light border-secondary',
        })
    )
    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'Password',
        })
    )
    password2 = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control bg-dark text-light border-secondary',
            'placeholder': 'Confirm password',
        })
    )
    
    class Meta:
        model = Person
        fields = ['email', 'first_name', 'last_name', 'role', 'password1', 'password2']


class WorkerProfileForm(forms.ModelForm):
    """Form for workers to update their profile"""
    
    class Meta:
        model = Person
        fields = [
            'profile_name', 'first_name', 'last_name', 'phone_number', 
            'date_of_birth', 'bio', 'interests', 'location', 'city',
            'latitude', 'longitude', 'hourly_rate', 'is_touring', 'is_available',
            'photo_1', 'photo_2', 'photo_3', 'photo_4', 'photo_5'
        ]
        widgets = {
            'profile_name': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'placeholder': 'Your stage name / alias',
            }),
            'first_name': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
            }),
            'phone_number': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'placeholder': '+64 XX XXX XXXX',
            }),
            'date_of_birth': forms.DateInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'type': 'date',
            }),
            'bio': forms.Textarea(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'rows': 4,
                'placeholder': 'Tell potential clients about yourself...',
            }),
            'interests': forms.Textarea(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'rows': 3,
                'placeholder': 'Your hobbies and interests...',
            }),
            'location': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'placeholder': 'Full address or area',
            }),
            'city': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'placeholder': 'City',
            }),
            'latitude': forms.NumberInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'step': '0.0000001',
            }),
            'longitude': forms.NumberInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'step': '0.0000001',
            }),
            'hourly_rate': forms.NumberInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'placeholder': 'Rate in NZD',
            }),
            'is_touring': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
            }),
            'is_available': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
            }),
            'photo_1': forms.FileInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'accept': 'image/*',
            }),
            'photo_2': forms.FileInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'accept': 'image/*',
            }),
            'photo_3': forms.FileInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'accept': 'image/*',
            }),
            'photo_4': forms.FileInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'accept': 'image/*',
            }),
            'photo_5': forms.FileInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'accept': 'image/*',
            }),
        }
    
    def clean(self):
        cleaned_data = super().clean()
        # Count uploaded photos
        photos = [
            cleaned_data.get('photo_1'),
            cleaned_data.get('photo_2'),
            cleaned_data.get('photo_3'),
        ]
        # Check existing photos if this is an update
        if self.instance and self.instance.pk:
            existing_photos = len(self.instance.get_photos())
            new_photos = len([p for p in photos if p])
            if existing_photos + new_photos < 3 and not all(photos):
                pass  # Allow saving with fewer photos during editing
        return cleaned_data


class ClientProfileForm(forms.ModelForm):
    """Form for clients to update their profile"""
    
    class Meta:
        model = Person
        fields = ['first_name', 'last_name', 'phone_number', 'date_of_birth']
        widgets = {
            'first_name': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
            }),
            'phone_number': forms.TextInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'placeholder': '+64 XX XXX XXXX',
            }),
            'date_of_birth': forms.DateInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'type': 'date',
            }),
        }


class ReferralForm(forms.ModelForm):
    """Form for creating/editing referrals"""
    
    class Meta:
        model = Referral
        fields = ['person', 'referral_date', 'referral_reason', 'action_due_date', 'status', 'notes']
        widgets = {
            'person': forms.Select(attrs={
                'class': 'form-select bg-dark text-light border-secondary',
            }),
            'referral_date': forms.DateInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'type': 'date',
            }),
            'referral_reason': forms.Textarea(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'rows': 3,
            }),
            'action_due_date': forms.DateInput(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'type': 'date',
            }),
            'status': forms.Select(attrs={
                'class': 'form-select bg-dark text-light border-secondary',
            }),
            'notes': forms.Textarea(attrs={
                'class': 'form-control bg-dark text-light border-secondary',
                'rows': 3,
            }),
        }


class ContactForm(forms.ModelForm):
    """Contact form for visitors"""
    
    class Meta:
        model = ContactMessage
        fields = ['email', 'phone', 'message']
        widgets = {
            'email': forms.EmailInput(attrs={
                'class': 'form-control bg-white text-dark',
                'placeholder': 'Enter email',
            }),
            'phone': forms.TextInput(attrs={
                'class': 'form-control bg-white text-dark',
                'placeholder': 'Enter Phone number',
            }),
            'message': forms.Textarea(attrs={
                'class': 'form-control bg-white text-dark',
                'rows': 6,
                'placeholder': 'Your message...',
            }),
        }


class PersonAdminForm(forms.ModelForm):
    """Admin form for managing people"""
    
    class Meta:
        model = Person
        fields = '__all__'
        exclude = ['password', 'last_login', 'groups', 'user_permissions']
        widgets = {
            'email': forms.EmailInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'role': forms.Select(attrs={'class': 'form-select bg-dark text-light border-secondary'}),
            'first_name': forms.TextInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'phone_number': forms.TextInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'date_of_birth': forms.DateInput(attrs={'class': 'form-control bg-dark text-light border-secondary', 'type': 'date'}),
            'profile_name': forms.TextInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'bio': forms.Textarea(attrs={'class': 'form-control bg-dark text-light border-secondary', 'rows': 3}),
            'interests': forms.Textarea(attrs={'class': 'form-control bg-dark text-light border-secondary', 'rows': 2}),
            'location': forms.TextInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'city': forms.TextInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'latitude': forms.NumberInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'longitude': forms.NumberInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'hourly_rate': forms.NumberInput(attrs={'class': 'form-control bg-dark text-light border-secondary'}),
            'is_touring': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_featured': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_available': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_staff': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'is_superuser': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }
