# parents/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView, TemplateView, FormView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.urls import reverse_lazy
from django.db.models import Q, Sum
from django.http import JsonResponse
from django.utils import timezone
from datetime import date, timedelta

from students.models import Student, ParentGuardian
from academics.models import Attendance
from finance.models import Invoice, Payment
from communication.models import Announcement, SMSMessage


# ========== PARENT AUTHENTICATION ==========

class ParentLoginView(FormView):
    """Parent login view"""
    template_name = 'parents/login.html'
    form_class = AuthenticationForm
    success_url = reverse_lazy('parents:parent_dashboard')
    
    def form_valid(self, form):
        username = self.request.POST.get('username')
        password = self.request.POST.get('password')
        
        user = authenticate(self.request, username=username, password=password)
        
        if user is not None and hasattr(user, 'parent_profile'):
            login(self.request, user)
            return super().form_valid(form)
        else:
            messages.error(self.request, 'Invalid credentials or not a parent account.')
            return self.form_invalid(form)
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Parent Portal Login'
        return context


class ParentLogoutView(LoginRequiredMixin, TemplateView):
    """Parent logout view"""
    
    def get(self, request, *args, **kwargs):
        logout(request)
        messages.success(request, 'You have been logged out successfully.')
        return redirect('parents:parent_login')


# ========== PARENT DASHBOARD ==========

class ParentDashboardView(LoginRequiredMixin, TemplateView):
    """Parent dashboard showing all linked students"""
    template_name = 'parents/dashboard.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get the parent profile
        if hasattr(self.request.user, 'parent_profile'):
            parent = self.request.user.parent_profile
        else:
            # If user is staff/admin, allow them to view as parent
            parent = ParentGuardian.objects.filter(email=self.request.user.email).first()
        
        if parent:
            # Get students linked to this parent
            students = Student.objects.filter(parents=parent)
            context['students'] = students
            context['parent'] = parent
            
            # Get recent announcements
            context['announcements'] = Announcement.objects.filter(
                is_published=True,
                audience__in=['all', 'parents']
            ).order_by('-publish_date')[:5]
            
            # Get pending payments across all students
            total_due = 0
            for student in students:
                due = Invoice.objects.filter(
                    student=student,
                    status__in=['sent', 'partial', 'overdue']
                ).aggregate(Sum('balance'))['balance__sum'] or 0
                total_due += due
            
            context['total_due'] = total_due
            
        return context


# ========== STUDENT VIEWS FOR PARENTS ==========

class ParentStudentDetailView(LoginRequiredMixin, DetailView):
    """View student details for parent"""
    model = Student
    template_name = 'parents/student_detail.html'
    context_object_name = 'student'
    
    def get_queryset(self):
        # Ensure parent can only see their own students
        if hasattr(self.request.user, 'parent_profile'):
            return Student.objects.filter(parents=self.request.user.parent_profile)
        return Student.objects.none()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get attendance summary
        today = date.today()
        month_start = today.replace(day=1)
        
        attendance_this_month = Attendance.objects.filter(
            student=self.object,
            date__gte=month_start
        )
        
        total_days = attendance_this_month.count()
        present_days = attendance_this_month.filter(status='present').count()
        
        context['attendance_rate'] = round((present_days / total_days) * 100, 1) if total_days > 0 else 0
        context['present_days'] = present_days
        context['total_days'] = total_days
        
        # Get recent attendance
        context['recent_attendance'] = Attendance.objects.filter(
            student=self.object
        ).order_by('-date')[:10]
        
        return context


class ParentStudentAttendanceView(LoginRequiredMixin, DetailView):
    """View student attendance for parent"""
    model = Student
    template_name = 'parents/student_attendance.html'
    context_object_name = 'student'
    
    def get_queryset(self):
        if hasattr(self.request.user, 'parent_profile'):
            return Student.objects.filter(parents=self.request.user.parent_profile)
        return Student.objects.none()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get date range
        year = self.request.GET.get('year', date.today().year)
        month = self.request.GET.get('month', date.today().month)
        
        try:
            year = int(year)
            month = int(month)
            start_date = date(year, month, 1)
            if month == 12:
                end_date = date(year + 1, 1, 1) - timedelta(days=1)
            else:
                end_date = date(year, month + 1, 1) - timedelta(days=1)
        except (ValueError, TypeError):
            start_date = date.today().replace(day=1)
            end_date = date.today()
        
        # Get attendance for the month
        attendances = Attendance.objects.filter(
            student=self.object,
            date__gte=start_date,
            date__lte=end_date
        ).order_by('date')
        
        context['attendances'] = attendances
        context['selected_year'] = year
        context['selected_month'] = month
        context['months'] = [
            (1, 'January'), (2, 'February'), (3, 'March'),
            (4, 'April'), (5, 'May'), (6, 'June'),
            (7, 'July'), (8, 'August'), (9, 'September'),
            (10, 'October'), (11, 'November'), (12, 'December')
        ]
        context['years'] = range(2020, date.today().year + 2)
        
        return context


class ParentStudentFeesView(LoginRequiredMixin, DetailView):
    """View student fees for parent"""
    model = Student
    template_name = 'parents/student_fees.html'
    context_object_name = 'student'
    
    def get_queryset(self):
        if hasattr(self.request.user, 'parent_profile'):
            return Student.objects.filter(parents=self.request.user.parent_profile)
        return Student.objects.none()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get all invoices for this student
        invoices = Invoice.objects.filter(student=self.object).order_by('-issue_date')
        context['invoices'] = invoices
        
        # Get payments
        payments = Payment.objects.filter(student=self.object).order_by('-payment_date')
        context['payments'] = payments
        
        # Summary
        total_invoiced = invoices.aggregate(Sum('total_amount'))['total_amount__sum'] or 0
        total_paid = payments.filter(status='completed').aggregate(Sum('amount'))['amount__sum'] or 0
        
        context['total_invoiced'] = total_invoiced
        context['total_paid'] = total_paid
        context['balance_due'] = total_invoiced - total_paid
        
        return context


class ParentStudentReportsView(LoginRequiredMixin, DetailView):
    """View student reports for parent"""
    model = Student
    template_name = 'parents/student_reports.html'
    context_object_name = 'student'
    
    def get_queryset(self):
        if hasattr(self.request.user, 'parent_profile'):
            return Student.objects.filter(parents=self.request.user.parent_profile)
        return Student.objects.none()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # This would link to generated reports
        # For now, we'll just show available report types
        context['report_types'] = [
            {'name': 'Term Report', 'url': '#'},
            {'name': 'Annual Report', 'url': '#'},
            {'name': 'Attendance Summary', 'url': '#'},
        ]
        
        return context


# ========== PARENT MESSAGES ==========

class ParentMessagesView(LoginRequiredMixin, ListView):
    """View messages for parent"""
    template_name = 'parents/messages.html'
    context_object_name = 'messages'
    
    def get_queryset(self):
        if hasattr(self.request.user, 'parent_profile'):
            parent = self.request.user.parent_profile
            # Find SMS messages sent to this parent's phone
            # Note: This filtering might need adjustment based on your SMSMessage model
            return SMSMessage.objects.filter(
                phone_numbers__icontains=parent.phone
            ).order_by('-sent_time') if parent.phone else SMSMessage.objects.none()
        return SMSMessage.objects.none()
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['unread_count'] = 0  # You could add an "is_read" field to track this
        return context


class ParentMessageDetailView(LoginRequiredMixin, DetailView):
    """View message details"""
    model = SMSMessage
    template_name = 'parents/message_detail.html'
    context_object_name = 'message'
    
    def get_queryset(self):
        if hasattr(self.request.user, 'parent_profile'):
            parent = self.request.user.parent_profile
            if parent and parent.phone:
                return SMSMessage.objects.filter(phone_numbers__icontains=parent.phone)
        return SMSMessage.objects.none()


# ========== PARENT PROFILE ==========

class ParentProfileView(LoginRequiredMixin, DetailView):
    """View parent profile"""
    template_name = 'parents/profile.html'
    context_object_name = 'parent'
    
    def get_object(self):
        if hasattr(self.request.user, 'parent_profile'):
            return self.request.user.parent_profile
        return get_object_or_404(ParentGuardian, email=self.request.user.email)


class ParentProfileEditView(LoginRequiredMixin, UpdateView):
    """Edit parent profile"""
    model = ParentGuardian
    fields = ['phone', 'alternate_phone', 'email', 'address', 'occupation', 'employer']
    template_name = 'parents/profile_edit.html'
    success_url = reverse_lazy('parents:parent_profile')
    
    def get_object(self):
        if hasattr(self.request.user, 'parent_profile'):
            return self.request.user.parent_profile
        return get_object_or_404(ParentGuardian, email=self.request.user.email)
    
    def form_valid(self, form):
        messages.success(self.request, 'Profile updated successfully!')
        return super().form_valid(form)