"""Web Views for Notifications App

This module provides web interface views for notification management,
including channels, rules, and notification history.
"""

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from django.views.generic import ListView, DetailView, CreateView, UpdateView
from django.http import JsonResponse
from django.db.models import Q
from django.urls import reverse_lazy
from django.contrib import messages

from .models import NotificationChannel, NotificationRule, Notification, NotificationTemplate
from .forms import NotificationChannelForm, NotificationTemplateForm, NotificationRuleForm


@method_decorator(login_required, name='dispatch')
class NotificationChannelListView(ListView):
    """List view for notification channels"""
    model = NotificationChannel
    template_name = 'notifications/channels/list.html'
    context_object_name = 'channels'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = NotificationChannel.objects.all().order_by('-created_at')
        search = self.request.GET.get('search')
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) | 
                Q(channel_type__icontains=search)
            )
        return queryset


@method_decorator(login_required, name='dispatch')
class NotificationListView(ListView):
    """List view for notifications"""
    model = Notification
    template_name = 'notifications/notification/list.html'
    context_object_name = 'notifications'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = Notification.objects.select_related('channel').order_by('-scheduled_at')
        status = self.request.GET.get('status')
        if status:
            queryset = queryset.filter(status=status)
        return queryset


@method_decorator(login_required, name='dispatch')
class NotificationRuleListView(ListView):
    """List view for notification rules"""
    model = NotificationRule
    template_name = 'notifications/rules/list.html'
    context_object_name = 'rules'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = NotificationRule.objects.select_related('channel').order_by('-created_at')
        return queryset


class NotificationChannelCreateView(LoginRequiredMixin, CreateView):
    """
    Create view for new notification channels.
    """
    
    model = NotificationChannel
    form_class = NotificationChannelForm
    template_name = 'notifications/channels/form.html'
    success_url = reverse_lazy('notifications:channel_list')
    
    def form_valid(self, form):
        """Set the current user as the channel creator."""
        form.instance.created_by = self.request.user
        messages.success(self.request, f'Notification channel "{form.instance.name}" created successfully!')
        return super().form_valid(form)


class NotificationChannelUpdateView(LoginRequiredMixin, UpdateView):
    """
    Update view for existing notification channels.
    """
    
    model = NotificationChannel
    form_class = NotificationChannelForm
    template_name = 'notifications/channels/form.html'
    success_url = reverse_lazy('notifications:channel_list')
    
    def form_valid(self, form):
        """Add success message after update."""
        messages.success(self.request, f'Notification channel "{form.instance.name}" updated successfully!')
        return super().form_valid(form)


class NotificationTemplateCreateView(LoginRequiredMixin, CreateView):
    """
    Create view for new notification templates.
    """
    
    model = NotificationTemplate
    form_class = NotificationTemplateForm
    template_name = 'notifications/notification/template_form.html'
    success_url = reverse_lazy('notifications:template_list')
    
    def form_valid(self, form):
        """Add success message after creation."""
        messages.success(self.request, f'Notification template "{form.instance.name}" created successfully!')
        return super().form_valid(form)


class NotificationTemplateUpdateView(LoginRequiredMixin, UpdateView):
    """
    Update view for existing notification templates.
    """
    
    model = NotificationTemplate
    form_class = NotificationTemplateForm
    template_name = 'notifications/notification/template_form.html'
    success_url = reverse_lazy('notifications:template_list')
    
    def form_valid(self, form):
        """Add success message after update."""
        messages.success(self.request, f'Notification template "{form.instance.name}" updated successfully!')
        return super().form_valid(form)


class NotificationRuleCreateView(LoginRequiredMixin, CreateView):
    """
    Create view for new notification rules.
    """
    
    model = NotificationRule
    form_class = NotificationRuleForm
    template_name = 'notifications/rules/form.html'
    success_url = reverse_lazy('notifications:rule_list')
    
    def form_valid(self, form):
        """Add success message after creation."""
        messages.success(self.request, f'Notification rule "{form.instance.name}" created successfully!')
        return super().form_valid(form)


class NotificationRuleUpdateView(LoginRequiredMixin, UpdateView):
    """
    Update view for existing notification rules.
    """
    
    model = NotificationRule
    form_class = NotificationRuleForm
    template_name = 'notifications/rules/form.html'
    success_url = reverse_lazy('notifications:rule_list')
    
    def form_valid(self, form):
        """Add success message after update."""
        messages.success(self.request, f'Notification rule "{form.instance.name}" updated successfully!')
        return super().form_valid(form)


@login_required
def live_notifications(request):
    """HTMX endpoint for live notification updates"""
    recent_notifications = Notification.objects.filter(
        status='sent'
    ).select_related('channel').order_by('-sent_at')[:5]
    
    return render(request, 'notifications/partials/live_notifications.html', {
        'notifications': recent_notifications
    })
