"""
Form Optimization Module

This module provides utilities for optimizing forms for conversions,
including field reduction, progress indicators, and mobile optimization.
"""

from django import forms
from django.forms.widgets import TextInput, EmailInput, Textarea, Select


class FormOptimizationMixin:
    """Mixin to add form optimization utilities"""
    
    def get_field_count(self):
        """Get the number of fields in the form"""
        return len(self.fields)
    
    def is_optimized_field_count(self):
        """Check if form has optimal field count (3-5 fields)"""
        field_count = self.get_field_count()
        return 3 <= field_count <= 5
    
    def get_required_fields(self):
        """Get list of required fields"""
        return [name for name, field in self.fields.items() if field.required]
    
    def get_optional_fields(self):
        """Get list of optional fields"""
        return [name for name, field in self.fields.items() if not field.required]
    
    def add_mobile_optimization(self):
        """Add mobile optimization attributes to all form fields"""
        for field_name, field in self.fields.items():
            # Add mobile-friendly attributes
            if hasattr(field.widget, 'attrs'):
                field.widget.attrs.update({
                    'class': field.widget.attrs.get('class', '') + ' form-control',
                    'autocomplete': self._get_autocomplete_value(field_name),
                })
                
                # Ensure minimum touch target size
                if not field.widget.attrs.get('style'):
                    field.widget.attrs['style'] = 'min-height: 44px;'
    
    def _get_autocomplete_value(self, field_name):
        """Get appropriate autocomplete value for field"""
        autocomplete_map = {
            'name': 'name',
            'email': 'email',
            'phone': 'tel',
            'company': 'organization',
            'address': 'street-address',
            'city': 'address-level2',
            'country': 'country-name',
            'postal_code': 'postal-code',
        }
        return autocomplete_map.get(field_name, 'off')


class OptimizedFormWidget(TextInput):
    """Base widget with mobile optimization"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.attrs.setdefault('class', 'form-control')
        self.attrs.setdefault('style', 'min-height: 44px;')


class OptimizedEmailWidget(EmailInput):
    """Email widget with mobile optimization"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.attrs.setdefault('class', 'form-control')
        self.attrs.setdefault('style', 'min-height: 44px;')
        self.attrs.setdefault('autocomplete', 'email')


class OptimizedPhoneWidget(TextInput):
    """Phone widget with mobile optimization"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.attrs.setdefault('type', 'tel')
        self.attrs.setdefault('class', 'form-control')
        self.attrs.setdefault('style', 'min-height: 44px;')
        self.attrs.setdefault('autocomplete', 'tel')


class OptimizedTextareaWidget(Textarea):
    """Textarea widget with mobile optimization"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.attrs.setdefault('class', 'form-control')
        self.attrs.setdefault('rows', 4)
        self.attrs.setdefault('style', 'min-height: 120px;')


class FormProgressIndicator:
    """Helper class for multi-step form progress tracking"""
    
    def __init__(self, total_steps):
        self.total_steps = total_steps
        self.current_step = 1
    
    def get_progress_percentage(self):
        """Get progress as percentage"""
        return round((self.current_step / self.total_steps) * 100)
    
    def get_progress_display(self):
        """Get progress display text"""
        return f"Step {self.current_step} of {self.total_steps}"
    
    def next_step(self):
        """Move to next step"""
        if self.current_step < self.total_steps:
            self.current_step += 1
    
    def previous_step(self):
        """Move to previous step"""
        if self.current_step > 1:
            self.current_step -= 1
    
    def is_first_step(self):
        """Check if on first step"""
        return self.current_step == 1
    
    def is_last_step(self):
        """Check if on last step"""
        return self.current_step == self.total_steps


class FormFieldOptimizer:
    """Utilities for optimizing individual form fields"""
    
    @staticmethod
    def get_optimal_field_order(form_fields):
        """Get optimal field order for conversions
        
        Recommended order:
        1. Name (required)
        2. Email (required)
        3. Phone (optional)
        4. Company (optional)
        5. Message (optional)
        """
        priority_order = ['name', 'email', 'phone', 'company', 'message', 'subject']
        ordered_fields = []
        
        for field_name in priority_order:
            if field_name in form_fields:
                ordered_fields.append(field_name)
        
        # Add any remaining fields
        for field_name in form_fields:
            if field_name not in ordered_fields:
                ordered_fields.append(field_name)
        
        return ordered_fields
    
    @staticmethod
    def get_field_placeholder(field_name):
        """Get appropriate placeholder text for field"""
        placeholders = {
            'name': 'Your Full Name',
            'email': 'your@email.com',
            'phone': '+44 (optional)',
            'company': 'Your Company',
            'subject': 'What can we help with?',
            'message': 'Tell us more about your needs...',
            'address': '123 Main Street',
            'city': 'London',
            'country': 'United Kingdom',
            'postal_code': 'SW1A 1AA',
        }
        return placeholders.get(field_name, '')
    
    @staticmethod
    def get_field_help_text(field_name):
        """Get appropriate help text for field"""
        help_texts = {
            'name': 'Your full name',
            'email': 'We\'ll use this to contact you',
            'phone': 'Optional - for faster response',
            'company': 'Your company name',
            'subject': 'Brief description of your inquiry',
            'message': 'Minimum 10 characters',
        }
        return help_texts.get(field_name, '')


class FormConversionOptimizer:
    """Main class for form conversion optimization"""
    
    @staticmethod
    def get_optimization_tips():
        """Get form optimization tips"""
        return {
            'field_count': {
                'ideal': '3-5 fields',
                'maximum': '7 fields',
                'impact': 'Each additional field reduces conversion by ~5-10%',
            },
            'field_order': {
                'first': 'Name (required)',
                'second': 'Email (required)',
                'third': 'Phone (optional)',
                'fourth': 'Company (optional)',
                'fifth': 'Message (optional)',
            },
            'mobile_optimization': {
                'input_types': 'Use appropriate input types (email, tel, number)',
                'autofill': 'Enable autofill for common fields',
                'touch_targets': 'Minimum 44x44px for buttons and inputs',
                'keyboard': 'Show appropriate keyboard for field type',
                'font_size': 'Minimum 16px to prevent zoom on iOS',
            },
            'progress_indicator': {
                'show_for': 'Multi-step forms (3+ steps)',
                'format': 'Step 1 of 3 or progress bar',
                'benefit': 'Reduces abandonment rate by ~10-15%',
            },
            'cta_button': {
                'size': 'Minimum 48x48px',
                'color': 'Contrasting color',
                'text': 'Action-oriented (Submit, Send, Get Started)',
                'placement': 'Below form, sticky on mobile',
            },
        }
    
    @staticmethod
    def validate_form_optimization(form):
        """Validate form optimization and return report"""
        report = {
            'field_count': len(form.fields),
            'is_optimized': len(form.fields) <= 5,
            'required_fields': len([f for f in form.fields.values() if f.required]),
            'optional_fields': len([f for f in form.fields.values() if not f.required]),
            'issues': [],
            'recommendations': [],
        }
        
        # Check field count
        if len(form.fields) > 7:
            report['issues'].append('Form has too many fields (>7)')
            report['recommendations'].append('Reduce to 3-5 fields for optimal conversion')
        elif len(form.fields) > 5:
            report['recommendations'].append('Consider reducing to 5 or fewer fields')
        
        # Check for mobile optimization
        for field_name, field in form.fields.items():
            if hasattr(field.widget, 'attrs'):
                if 'class' not in field.widget.attrs:
                    report['recommendations'].append(f'Add CSS class to {field_name} for styling')
                if 'autocomplete' not in field.widget.attrs:
                    report['recommendations'].append(f'Add autocomplete attribute to {field_name}')
        
        return report
