# communication/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.utils import timezone
import csv

from .models import SMSMessage, Announcement
from students.models import Student, ParentGuardian
from staff.models import Staff

# ========== ANNOUNCEMENT VIEWS ==========

class AnnouncementListView(LoginRequiredMixin, ListView):
    """List all announcements"""
    model = Announcement
    template_name = 'communication/announcements.html'
    context_object_name = 'announcements'
    paginate_by = 10
    
    def get_queryset(self):
        queryset = Announcement.objects.all()
        
        # Filter by audience
        audience = self.request.GET.get('audience')
        if audience:
            queryset = queryset.filter(audience=audience)
        
        # Filter by priority
        priority = self.request.GET.get('priority')
        if priority:
            queryset = queryset.filter(priority=priority)
        
        # Filter by published status
        published = self.request.GET.get('published')
        if published == 'published':
            queryset = queryset.filter(is_published=True)
        elif published == 'draft':
            queryset = queryset.filter(is_published=False)
        
        return queryset.order_by('-publish_date', '-priority')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['audience_choices'] = Announcement.AUDIENCE_CHOICES
        context['priority_choices'] = Announcement.PRIORITY_CHOICES
        context['published_count'] = Announcement.objects.filter(is_published=True).count()
        context['draft_count'] = Announcement.objects.filter(is_published=False).count()
        return context

class AnnouncementDetailView(LoginRequiredMixin, DetailView):
    """View announcement details"""
    model = Announcement
    template_name = 'communication/announcement_detail.html'
    context_object_name = 'announcement'

class AnnouncementCreateView(LoginRequiredMixin, CreateView):
    """Create a new announcement"""
    model = Announcement
    fields = ['title', 'content', 'audience', 'priority', 'publish_date', 'is_published']
    template_name = 'communication/announcement_form.html'
    success_url = reverse_lazy('communication:announcement_list')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Create New Announcement'
        return context
    
    def form_valid(self, form):
        messages.success(self.request, 'Announcement created successfully!')
        return super().form_valid(form)

class AnnouncementUpdateView(LoginRequiredMixin, UpdateView):
    """Update an announcement"""
    model = Announcement
    fields = ['title', 'content', 'audience', 'priority', 'publish_date', 'is_published']
    template_name = 'communication/announcement_form.html'
    success_url = reverse_lazy('communication:announcement_list')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = f'Edit: {self.object.title}'
        return context
    
    def form_valid(self, form):
        messages.success(self.request, 'Announcement updated successfully!')
        return super().form_valid(form)

class AnnouncementDeleteView(LoginRequiredMixin, DeleteView):
    """Delete an announcement"""
    model = Announcement
    success_url = reverse_lazy('communication:announcement_list')
    template_name = 'communication/announcement_confirm_delete.html'
    
    def delete(self, request, *args, **kwargs):
        messages.success(request, 'Announcement deleted successfully!')
        return super().delete(request, *args, **kwargs)

def publish_announcement(request, pk):
    """Publish an announcement"""
    announcement = get_object_or_404(Announcement, pk=pk)
    announcement.is_published = True
    announcement.save()
    messages.success(request, f'Announcement "{announcement.title}" published.')
    return redirect('communication:announcement_detail', pk=pk)

def unpublish_announcement(request, pk):
    """Unpublish an announcement"""
    announcement = get_object_or_404(Announcement, pk=pk)
    announcement.is_published = False
    announcement.save()
    messages.success(request, f'Announcement "{announcement.title}" unpublished.')
    return redirect('communication:announcement_detail', pk=pk)

# ========== SMS MESSAGE VIEWS ==========

class SMSMessageListView(LoginRequiredMixin, ListView):
    """List all SMS messages"""
    model = SMSMessage
    template_name = 'communication/sms_list.html'
    context_object_name = 'messages'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = SMSMessage.objects.all()
        
        # Filter by message type
        msg_type = self.request.GET.get('type')
        if msg_type:
            queryset = queryset.filter(message_type=msg_type)
        
        # Filter by status
        status = self.request.GET.get('status')
        if status:
            queryset = queryset.filter(status=status)
        
        return queryset.order_by('-sent_time')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['message_types'] = SMSMessage.MESSAGE_TYPE_CHOICES
        context['status_choices'] = SMSMessage.STATUS_CHOICES
        return context

class SMSMessageDetailView(LoginRequiredMixin, DetailView):
    """View SMS message details"""
    model = SMSMessage
    template_name = 'communication/sms_detail.html'
    context_object_name = 'sms'

class SMSComposeView(LoginRequiredMixin, TemplateView):
    """Compose and send SMS messages"""
    template_name = 'communication/sms_compose.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get recipients based on type
        recipient_type = self.request.GET.get('recipient_type', 'all')
        
        if recipient_type == 'parents':
            context['recipients'] = ParentGuardian.objects.filter(receive_sms=True).select_related('student')
            context['recipient_count'] = ParentGuardian.objects.filter(receive_sms=True).count()
        elif recipient_type == 'staff':
            context['recipients'] = Staff.objects.filter(is_active=True)
            context['recipient_count'] = Staff.objects.filter(is_active=True).count()
        elif recipient_type == 'class':
            class_id = self.request.GET.get('class_id')
            if class_id:
                from academics.models import SchoolClass
                school_class = get_object_or_404(SchoolClass, pk=class_id)
                students = Student.objects.filter(current_class=school_class)
                context['recipients'] = ParentGuardian.objects.filter(student__in=students, receive_sms=True)
                context['recipient_count'] = context['recipients'].count()
                context['selected_class'] = school_class
        else:
            # All parents
            context['recipients'] = ParentGuardian.objects.filter(receive_sms=True)
            context['recipient_count'] = ParentGuardian.objects.filter(receive_sms=True).count()
        
        context['message_types'] = SMSMessage.MESSAGE_TYPE_CHOICES
        context['recipient_type'] = recipient_type
        
        return context
    
    def post(self, request, *args, **kwargs):
        message_type = request.POST.get('message_type')
        message = request.POST.get('message')
        recipient_ids = request.POST.getlist('recipients')
        
        if not message or not recipient_ids:
            messages.error(request, 'Please enter a message and select recipients.')
            return redirect('communication:sms_compose')
        
        # Get phone numbers
        recipients = ParentGuardian.objects.filter(id__in=recipient_ids)
        phone_numbers = [r.phone for r in recipients if r.phone]
        
        # Create SMS record
        sms = SMSMessage.objects.create(
            message_type=message_type,
            message=message,
            phone_numbers=phone_numbers,
            status='sent',
            sent_time=timezone.now()
        )
        
        # In a real app, you'd integrate with an SMS gateway here
        # For now, we'll just simulate sending
        
        messages.success(request, f'SMS sent to {len(phone_numbers)} recipients!')
        return redirect('communication:sms_detail', pk=sms.pk)

# ========== PARENT COMMUNICATION ==========

class ParentCommunicationView(LoginRequiredMixin, TemplateView):
    """Parent communication dashboard"""
    template_name = 'communication/parent_communication.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get students with parent contacts
        students = Student.objects.filter(status='active').prefetch_related('parents')
        
        parent_list = []
        for student in students:
            parents = student.parents.all()
            for parent in parents:
                parent_list.append({
                    'student': student,
                    'parent': parent,
                    'phone': parent.phone,
                    'email': parent.email,
                    'preferred_language': parent.preferred_language,
                    'receive_sms': parent.receive_sms
                })
        
        context['parents'] = parent_list
        context['total_parents'] = len(parent_list)
        
        return context

def send_message_to_parent(request, parent_id):
    """Send a message to a specific parent"""
    parent = get_object_or_404(ParentGuardian, pk=parent_id)
    
    if request.method == 'POST':
        message = request.POST.get('message')
        message_type = request.POST.get('message_type', 'general')
        
        if message and parent.phone:
            # Create SMS record
            sms = SMSMessage.objects.create(
                message_type=message_type,
                message=message,
                phone_numbers=[parent.phone],
                status='sent',
                sent_time=timezone.now()
            )
            
            messages.success(request, f'Message sent to {parent.get_full_name()}')
            return redirect('communication:sms_detail', pk=sms.pk)
    
    return render(request, 'communication/parent_message_form.html', {'parent': parent})

# ========== API ENDPOINTS ==========

def get_announcement_stats(request):
    """API endpoint for announcement statistics"""
    stats = {
        'total': Announcement.objects.count(),
        'published': Announcement.objects.filter(is_published=True).count(),
        'draft': Announcement.objects.filter(is_published=False).count(),
        'by_audience': list(Announcement.objects.values('audience').annotate(count=Count('id'))),
        'by_priority': list(Announcement.objects.values('priority').annotate(count=Count('id'))),
    }
    return JsonResponse(stats)

def get_sms_stats(request):
    """API endpoint for SMS statistics"""
    stats = {
        'total': SMSMessage.objects.count(),
        'sent': SMSMessage.objects.filter(status='sent').count(),
        'failed': SMSMessage.objects.filter(status='failed').count(),
        'by_type': list(SMSMessage.objects.values('message_type').annotate(count=Count('id'))),
    }
    return JsonResponse(stats)