"""
Appreciation forms
"""
from django import forms
from django.utils.translation import gettext_lazy as _

from .models import (
    Appreciation,
    AppreciationAttachment,
    AppreciationCategory,
    AppreciationComment,
    AppreciationStatus,
    AppreciationType,
)


class AppreciationCategoryForm(forms.ModelForm):
    """Form for AppreciationCategory"""

    class Meta:
        model = AppreciationCategory
        fields = ['name', 'description', 'is_active', 'display_order']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Category name')
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 3,
                'placeholder': _('Description')
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
            'display_order': forms.NumberInput(attrs={
                'class': 'form-control',
                'min': 0
            }),
        }


class AppreciationForm(forms.ModelForm):
    """Form for Appreciation"""
    submitter_role = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Your role, e.g., Nurse Manager')
        })
    )

    class Meta:
        model = Appreciation
        fields = [
            'title',
            'description',
            'story',
            'appreciation_type',
            'category',
            'recipient_name',
            'recipient_type',
            'recipient_id',
            'submitter_role',
            'tags',
            'is_public',
            'share_on_dashboard',
            'share_in_newsletter',
        ]
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Appreciation title')
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 5,
                'placeholder': _('Describe the appreciation')
            }),
            'story': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 8,
                'placeholder': _('Tell the story behind this appreciation')
            }),
            'appreciation_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'category': forms.Select(attrs={
                'class': 'form-select'
            }),
            'recipient_name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('Name of person or team')
            }),
            'recipient_type': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('e.g., Staff, Patient, Department')
            }),
            'recipient_id': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': _('System ID if applicable')
            }),
            'tags': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 2,
                'placeholder': _('Comma-separated tags')
            }),
            'is_public': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
            'share_on_dashboard': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
            'share_in_newsletter': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
        }

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        hospital = kwargs.pop('hospital', None)
        super().__init__(*args, **kwargs)

        # Filter categories to active ones only
        if self.fields.get('category'):
            self.fields['category'].queryset = AppreciationCategory.objects.filter(
                is_active=True
            ).order_by('display_order', 'name')

        # Set default values based on context
        if user and not self.instance.pk:
            self.instance.submitted_by = user

        if hospital and not self.instance.pk:
            self.instance.hospital = hospital

    def clean_tags(self):
        tags = self.cleaned_data.get('tags', '')
        if tags:
            # Convert comma-separated string to list
            return [tag.strip() for tag in tags.split(',') if tag.strip()]
        return []


class AppreciationSubmitForm(AppreciationForm):
    """Form for submitting an appreciation (sets status to submitted)"""

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.status = AppreciationStatus.SUBMITTED
        if commit:
            instance.save()
        return instance


class AppreciationAcknowledgeForm(forms.ModelForm):
    """Form for acknowledging an appreciation"""
    acknowledgment_notes = forms.CharField(
        required=True,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 4,
            'placeholder': _('Add your acknowledgment notes here')
        })
    )

    class Meta:
        model = Appreciation
        fields = ['acknowledgment_notes']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

        if user and not self.instance.pk:
            self.instance.acknowledged_by = user


class AppreciationAttachmentForm(forms.ModelForm):
    """Form for uploading appreciation attachments"""
    description = forms.CharField(
        required=False,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 2,
            'placeholder': _('Describe the attachment')
        })
    )

    class Meta:
        model = AppreciationAttachment
        fields = ['file', 'description']
        widgets = {
            'file': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*,.pdf,.doc,.docx'
            }),
        }

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

        if user and not self.instance.pk:
            self.instance.uploaded_by = user

    def save(self, commit=True):
        instance = super().save(commit=False)

        # Extract file information
        if instance.file:
            instance.filename = instance.file.name
            instance.file_type = instance.file.content_type
            instance.file_size = instance.file.size

        if commit:
            instance.save()
        return instance


class AppreciationCommentForm(forms.ModelForm):
    """Form for adding comments to appreciations"""
    comment = forms.CharField(
        required=True,
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 3,
            'placeholder': _('Write your comment here')
        })
    )
    is_internal = forms.BooleanField(
        required=False,
        label=_('Internal Comment'),
        help_text=_('Check if this is an internal comment only visible to staff'),
        widget=forms.CheckboxInput(attrs={
            'class': 'form-check-input'
        })
    )

    class Meta:
        model = AppreciationComment
        fields = ['comment', 'is_internal']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        appreciation = kwargs.pop('appreciation', None)
        super().__init__(*args, **kwargs)

        if user and not self.instance.pk:
            self.instance.user = user

        if appreciation and not self.instance.pk:
            self.instance.appreciation = appreciation


class AppreciationFilterForm(forms.Form):
    """Form for filtering appreciations"""
    search = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('Search appreciations...')
        })
    )
    status = forms.ChoiceField(
        required=False,
        choices=[('', _('All Statuses'))] + AppreciationStatus.choices,
        widget=forms.Select(attrs={
            'class': 'form-select'
        })
    )
    appreciation_type = forms.ChoiceField(
        required=False,
        choices=[('', _('All Types'))] + AppreciationType.choices,
        widget=forms.Select(attrs={
            'class': 'form-select'
        })
    )
    category = forms.ModelChoiceField(
        required=False,
        queryset=AppreciationCategory.objects.filter(
            is_active=True
        ).order_by('display_order', 'name'),
        empty_label=_('All Categories'),
        widget=forms.Select(attrs={
            'class': 'form-select'
        })
    )
    date_from = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control',
            'type': 'date'
        })
    )
    date_to = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'class': 'form-control',
            'type': 'date'
        })
    )
    is_public = forms.BooleanField(
        required=False,
        widget=forms.CheckboxInput(attrs={
            'class': 'form-check-input'
        })
    )