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

This module contains forms for the pages application.
Provides forms for creating and editing user pages.

Author: Focus Development Team
Version: 1.0.0
Created: 2025-01-01
"""

from django import forms
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError

from .models import Page, PageStatus, PageVisibility


class PageForm(forms.ModelForm):
    """
    Form for creating and editing pages.
    
    Provides a comprehensive form for page creation and editing
    with validation, auto-slug generation, and rich text support.
    """
    
    class Meta:
        model = Page
        fields = [
            'title', 'slug', 'content', 'excerpt', 'status', 'visibility',
            'featured_image', 'meta_description', 'meta_keywords', 
            'custom_css', 'is_featured', 'tags'
        ]
        
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Enter page title'),
                'maxlength': 200,
            }),
            'slug': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('URL-friendly identifier (auto-generated)'),
                'maxlength': 200,
            }),
            'content': forms.Textarea(attrs={
                'class': 'form-control rich-text-editor',
                'rows': 15,
                'placeholder': _('Write your page content here...'),
            }),
            'excerpt': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': _('Brief description or summary (optional)'),
                'maxlength': 500,
            }),
            'status': forms.Select(attrs={
                'class': 'form-select',
            }),
            'visibility': forms.Select(attrs={
                'class': 'form-select',
            }),
            'featured_image': forms.URLInput(attrs={
                'class': 'form-control',
                'placeholder': _('https://example.com/image.jpg'),
            }),
            'meta_description': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('SEO meta description (optional)'),
                'maxlength': 160,
            }),
            'meta_keywords': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('keyword1, keyword2, keyword3'),
                'maxlength': 255,
            }),
            'custom_css': forms.Textarea(attrs={
                'class': 'form-control code-editor',
                'rows': 8,
                'placeholder': _('/* Custom CSS for this page */'),
            }),
            'is_featured': forms.CheckboxInput(attrs={
                'class': 'form-check-input',
            }),
            'tags': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('tag1, tag2, tag3'),
                'maxlength': 500,
            }),
        }
        
        labels = {
            'title': _('Page Title'),
            'slug': _('URL Slug'),
            'content': _('Content'),
            'excerpt': _('Excerpt'),
            'status': _('Status'),
            'visibility': _('Visibility'),
            'featured_image': _('Featured Image URL'),
            'meta_description': _('Meta Description'),
            'meta_keywords': _('Meta Keywords'),
            'custom_css': _('Custom CSS'),
            'is_featured': _('Featured Page'),
            'tags': _('Tags'),
        }
        
        help_texts = {
            'title': _('The main title of your page (3-200 characters)'),
            'slug': _('URL-friendly identifier. Leave blank to auto-generate from title.'),
            'content': _('The main content of your page. HTML is supported.'),
            'excerpt': _('A brief summary that appears in page listings (max 500 characters)'),
            'status': _('Draft pages are only visible to you. Published pages are live.'),
            'visibility': _('Private: Only you can see it. Public: Everyone can see it. Unlisted: Only people with the link can see it.'),
            'featured_image': _('Optional image URL to display with your page'),
            'meta_description': _('Description for search engines (max 160 characters)'),
            'meta_keywords': _('Keywords for SEO, separated by commas'),
            'custom_css': _('Custom CSS styling for this page only'),
            'is_featured': _('Featured pages appear prominently in listings'),
            'tags': _('Tags for categorization, separated by commas'),
        }
    
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # Make slug field optional for new pages
        if not self.instance.pk:
            self.fields['slug'].required = False
    
    def clean_title(self):
        """Validate and clean the title field."""
        title = self.cleaned_data.get('title')
        if title:
            title = title.strip()
            if len(title) < 3:
                raise ValidationError(_('Title must be at least 3 characters long.'))
        return title
    
    def clean_slug(self):
        """Validate and clean the slug field."""
        slug = self.cleaned_data.get('slug')
        title = self.cleaned_data.get('title')
        
        # Auto-generate slug if not provided
        if not slug and title:
            slug = slugify(title)
        
        if slug:
            # Check for uniqueness
            existing = Page.objects.filter(slug=slug)
            if self.instance.pk:
                existing = existing.exclude(pk=self.instance.pk)
            
            if existing.exists():
                raise ValidationError(_('A page with this slug already exists.'))
        
        return slug
    
    def clean_tags(self):
        """Validate and clean the tags field."""
        tags = self.cleaned_data.get('tags', '')
        if tags:
            # Clean up tags: remove extra spaces, empty tags
            tag_list = [tag.strip() for tag in tags.split(',') if tag.strip()]
            return ', '.join(tag_list)
        return tags
    
    def clean_custom_css(self):
        """Basic validation for custom CSS."""
        css = self.cleaned_data.get('custom_css', '')
        if css:
            # Basic security check - prevent dangerous CSS
            dangerous_patterns = ['javascript:', '@import', 'expression(']
            css_lower = css.lower()
            for pattern in dangerous_patterns:
                if pattern in css_lower:
                    raise ValidationError(_('Custom CSS contains potentially dangerous content.'))
        return css
    
    def save(self, commit=True):
        """Save the page with the current user as author."""
        page = super().save(commit=False)
        
        if self.user and not page.author_id:
            page.author = self.user
        
        # Auto-generate slug if not provided
        if not page.slug and page.title:
            page.slug = slugify(page.title)
        
        if commit:
            page.save()
        
        return page


class PageSearchForm(forms.Form):
    """
    Form for searching and filtering pages.
    """
    
    search = forms.CharField(
        max_length=200,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Search pages...'),
        }),
        label=_('Search')
    )
    
    status = forms.ChoiceField(
        choices=[('', _('All Statuses'))] + PageStatus.choices,
        required=False,
        widget=forms.Select(attrs={
            'class': 'form-select',
        }),
        label=_('Status')
    )
    
    visibility = forms.ChoiceField(
        choices=[('', _('All Visibility'))] + PageVisibility.choices,
        required=False,
        widget=forms.Select(attrs={
            'class': 'form-select',
        }),
        label=_('Visibility')
    )
    
    is_featured = forms.ChoiceField(
        choices=[
            ('', _('All Pages')),
            ('true', _('Featured Only')),
            ('false', _('Non-Featured Only')),
        ],
        required=False,
        widget=forms.Select(attrs={
            'class': 'form-select',
        }),
        label=_('Featured')
    )
    
    tags = forms.CharField(
        max_length=200,
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Filter by tags...'),
        }),
        label=_('Tags')
    )
    
    sort_by = forms.ChoiceField(
        choices=[
            ('-created_at', _('Newest First')),
            ('created_at', _('Oldest First')),
            ('title', _('Title A-Z')),
            ('-title', _('Title Z-A')),
            ('-view_count', _('Most Viewed')),
            ('-published_at', _('Recently Published')),
        ],
        required=False,
        widget=forms.Select(attrs={
            'class': 'form-select',
        }),
        label=_('Sort By')
    )