# staff/forms.py
from django import forms
from django.contrib.auth import get_user_model
from .models import Staff, StaffLeave, StaffAttendance

User = get_user_model()


class StaffUserForm(forms.ModelForm):
    """Form for creating/updating the Django User account linked to a staff member.

    Notes:
        - Do NOT put title/honorific (Mr, Mme, Dr) in First Name.
        - First Name: given name only, e.g. 'Annie'
        - Last Name: family name only, e.g. 'Shey'
        - Username: auto-suggested as firstname.lastname (no title)
    """
    password = forms.CharField(widget=forms.PasswordInput, required=False,
                               help_text="Leave blank to keep existing password")
    confirm_password = forms.CharField(widget=forms.PasswordInput, required=False,
                                       label="Confirm Password")

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'password']
        labels = {
            'first_name': 'First Name (given name only — no title)',
            'last_name':  'Last Name (family name)',
        }
        help_texts = {
            'username':   "Format: firstname.lastname — e.g. annie.shey",
            'first_name': "⚠️ Do NOT write 'Mme Annie' — write 'Annie' only. Set title in the Staff Profile below.",
        }

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm  = cleaned_data.get('confirm_password')
        if password and password != confirm:
            raise forms.ValidationError("Passwords do not match")
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data.get('password')
        if password:
            user.set_password(password)
        if commit:
            user.save()
        return user


class StaffForm(forms.ModelForm):
    """Form for the Staff profile record (not the User account).

    Sensitive payroll fields (salary, bank_account, tax_id, social_security)
    are excluded — edit those via the Django admin only.
    """

    class Meta:
        model = Staff
        # Explicit safe list — keeps salary/bank/tax out of the web form
        fields = [
            'title',
            'school',
            'date_of_birth', 'gender', 'nationality', 'marital_status',
            'phone_country_code', 'phone_number',
            'alt_phone_country_code', 'alternate_phone',
            'email', 'address', 'quarter', 'city',
            'emergency_contact_name',
            'emergency_phone_country_code', 'emergency_contact_phone',
            'emergency_contact_relationship',
            'role', 'department', 'employment_status',
            'hire_date', 'contract_end_date',
            'qualifications', 'specialization', 'years_of_experience',
            'subjects_taught', 'is_class_teacher', 'homeroom_class',
            'bank_name', 'bank_branch',
            'photo', 'cv_file', 'contract_file', 'id_document', 'diplomas',
            'is_active', 'notes',
        ]
        widgets = {
            'date_of_birth':    forms.DateInput(attrs={'type': 'date'}),
            'hire_date':        forms.DateInput(attrs={'type': 'date'}),
            'contract_end_date':forms.DateInput(attrs={'type': 'date'}),
            'address':          forms.Textarea(attrs={'rows': 3}),
            'notes':            forms.Textarea(attrs={'rows': 3}),
            'qualifications':   forms.Textarea(attrs={'rows': 3}),
            'phone_country_code':           forms.Select(attrs={'class': 'phone-code-select'}),
            'alt_phone_country_code':       forms.Select(attrs={'class': 'phone-code-select'}),
            'emergency_phone_country_code': forms.Select(attrs={'class': 'phone-code-select'}),
            'phone_number':           forms.TextInput(attrs={'placeholder': '670177979'}),
            'alternate_phone':        forms.TextInput(attrs={'placeholder': '670177979'}),
            'emergency_contact_phone':forms.TextInput(attrs={'placeholder': '670177979'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['date_of_birth'].required = False
        self.fields['phone_number'].required = False
        self.fields['email'].required = False
        self.fields['address'].required = False
        self.fields['alternate_phone'].required = False
        self.fields['emergency_contact_phone'].required = False


class StaffLeaveForm(forms.ModelForm):
    """Form for staff leave requests."""

    class Meta:
        model = StaffLeave
        fields = ['leave_type', 'start_date', 'end_date', 'reason']
        widgets = {
            'start_date': forms.DateInput(attrs={'type': 'date'}),
            'end_date':   forms.DateInput(attrs={'type': 'date'}),
            'reason':     forms.Textarea(attrs={'rows': 3}),
        }

    def clean(self):
        cleaned_data = super().clean()
        start = cleaned_data.get('start_date')
        end   = cleaned_data.get('end_date')
        if start and end and end < start:
            raise forms.ValidationError("End date cannot be before start date")
        return cleaned_data


class StaffAttendanceForm(forms.ModelForm):
    """Form for staff attendance."""

    class Meta:
        model = StaffAttendance
        fields = ['staff', 'date', 'check_in_time', 'check_out_time', 'status', 'remarks']
        widgets = {
            'date':           forms.DateInput(attrs={'type': 'date'}),
            'check_in_time':  forms.TimeInput(attrs={'type': 'time'}),
            'check_out_time': forms.TimeInput(attrs={'type': 'time'}),
        }


class StaffImportForm(forms.Form):
    """Form for importing staff from Excel/CSV."""
    file = forms.FileField(
        label='Excel / CSV File',
        help_text=(
            'Columns required: Title, First Name, Last Name, Role, Department, '
            'Phone, Email, Hire Date. '
            'Title column: Mr, Mme, Mrs, Dr etc. — NOT inside First Name.'
        )
    )

    def clean_file(self):
        file = self.cleaned_data['file']
        if not file.name.endswith(('.xlsx', '.xls', '.csv')):
            raise forms.ValidationError('Please upload an Excel or CSV file')
        return file


class StaffSearchForm(forms.Form):
    """Form for searching/filtering the staff list."""
    q = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'placeholder': 'Search by name, ID, or phone…'})
    )
    role = forms.ChoiceField(
        required=False,
        choices=[('', 'All Roles')] + Staff.ROLE_CHOICES
    )
    department = forms.ChoiceField(
        required=False,
        choices=[('', 'All Departments')] + Staff.DEPARTMENT_CHOICES
    )
    status = forms.ChoiceField(
        required=False,
        choices=[('', 'All Status'), ('active', 'Active'), ('inactive', 'Inactive')]
    )