"""
Forms for Organizations app
"""
from django import forms
from .models import Department, Hospital, Organization, Patient, Staff


class StaffForm(forms.ModelForm):
    """Form for creating and updating Staff"""
    
    class Meta:
        model = Staff
        fields = [
            'first_name', 'last_name', 'first_name_ar', 'last_name_ar',
            'staff_type', 'job_title', 'license_number', 'specialization',
            'employee_id', 'email', 'hospital', 'department', 'status'
        ]
        widgets = {
            'first_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter first name'
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter last name'
            }),
            'first_name_ar': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'الاسم الأول',
                'dir': 'rtl'
            }),
            'last_name_ar': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'اسم العائلة',
                'dir': 'rtl'
            }),
            'staff_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'job_title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter job title'
            }),
            'license_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter license number'
            }),
            'specialization': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter specialization'
            }),
            'employee_id': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter employee ID'
            }),
            'email': forms.EmailInput(attrs={
                'class': 'form-control',
                'placeholder': 'Enter email address'
            }),
            'hospital': forms.Select(attrs={
                'class': 'form-select'
            }),
            'department': forms.Select(attrs={
                'class': 'form-select'
            }),
            'status': forms.Select(attrs={
                'class': 'form-select'
            }),
        }
    
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # Filter hospitals based on user role
        if user and not user.is_px_admin() and user.hospital:
            self.fields['hospital'].queryset = Hospital.objects.filter(id=user.hospital.id)
            self.fields['hospital'].initial = user.hospital
            self.fields['hospital'].widget.attrs['readonly'] = True
        
        # Filter departments based on selected hospital
        if self.instance and self.instance.pk:
            # Updating existing staff - filter by their hospital
            if self.instance.hospital:
                self.fields['department'].queryset = Department.objects.filter(hospital=self.instance.hospital)
            else:
                self.fields['department'].queryset = Department.objects.none()
        elif user and user.hospital:
            # Creating new staff - filter by user's hospital
            self.fields['department'].queryset = Department.objects.filter(hospital=user.hospital)
        else:
            self.fields['department'].queryset = Department.objects.none()
    
    def clean_employee_id(self):
        """Validate that employee_id is unique"""
        employee_id = self.cleaned_data.get('employee_id')
        
        # Skip validation if this is an update and employee_id hasn't changed
        if self.instance.pk and self.instance.employee_id == employee_id:
            return employee_id
        
        # Check if employee_id already exists
        if Staff.objects.filter(employee_id=employee_id).exists():
            raise forms.ValidationError("A staff member with this Employee ID already exists.")
        
        return employee_id
    
    def clean_email(self):
        """Clean email field"""
        email = self.cleaned_data.get('email')
        if email:
            return email.lower().strip()
        return email


class OrganizationForm(forms.ModelForm):
    """Form for creating and updating Organization"""
    
    class Meta:
        model = Organization
        fields = [
            'name', 'name_ar', 'code', 'address', 'city',
            'phone', 'email', 'website', 'license_number', 'status', 'logo'
        ]


class HospitalForm(forms.ModelForm):
    """Form for creating and updating Hospital"""
    
    class Meta:
        model = Hospital
        fields = [
            'organization', 'name', 'name_ar', 'code',
            'address', 'city', 'phone', 'email',
            'license_number', 'capacity', 'status'
        ]


class DepartmentForm(forms.ModelForm):
    """Form for creating and updating Department"""
    
    class Meta:
        model = Department
        fields = [
            'hospital', 'name', 'name_ar', 'code',
            'parent', 'manager', 'phone', 'email',
            'location', 'status'
        ]


class PatientForm(forms.ModelForm):
    """Form for creating and updating Patient"""
    
    class Meta:
        model = Patient
        fields = [
            'mrn', 'national_id', 'first_name', 'last_name',
            'first_name_ar', 'last_name_ar', 'date_of_birth',
            'gender', 'phone', 'email', 'address', 'city',
            'primary_hospital', 'status'
        ]
