from rest_framework.views import APIView
from rest_framework.response import Response
from tasks.models import TaskManager  
from crm.models import ( 
    Payment, Invoice, Lead, CollectionData
)
from django.db.models.functions import TruncMonth
from django.utils import timezone
from django.db.models import Sum


class DashboardStatsAPIView(APIView):

    def get(self, request):

        # Task Manager (replace Task)
        total_tasks_completed = TaskManager.objects.filter(designed_status='completed').count()
        print(total_tasks_completed, "total_tasks_completed")
        total_tasks_pending = TaskManager.objects.exclude(designed_status='completed').count()
        print(total_tasks_pending, "total_tasks_pending")

        # Payments
        total_amount = Payment.objects.aggregate(total=Sum('amount'))['total'] or 0
        print(total_amount, "total_amount")

        # Late Amount: invoices that are overdue and not paid
        now = timezone.now().date()
        late_invoices = Invoice.objects.filter(
            invoice_date__lt=now,
            is_paid=False
        )
        late_amount = late_invoices.aggregate(total=Sum('pending_amount'))['total'] or 0

        # Activate Users
        activate_customer = Invoice.objects.filter(approved=True).count()

        # Total Lead 
        total_leads = Lead.objects.all().count()
        total_leads_convert = Lead.objects.filter(is_converted=True).count()
        total_collections = CollectionData.objects.all().count()
        

        collections_monthly = (
            CollectionData.objects
            .annotate(month=TruncMonth('created_at'))
            .values('month')
            .annotate(count=Sum(1))
            .order_by('month')
        )
       
        collections_monthly_data = [
            {
                "month": entry["month"].strftime("%Y-%m") if entry["month"] else None,
                "count": entry["count"]
            }
            for entry in collections_monthly
        ]

        data = {
            "total_tasks_completed": total_tasks_completed,
            "total_tasks_pending": total_tasks_pending,
            "total_amount": total_amount,
            "late_amount": late_amount,
            "activate_customer": activate_customer,
            "total_leads": total_leads,
            "total_leads_converted": total_leads_convert,
            "total_collections": total_collections,
            "collections_monthly_data": collections_monthly_data,
        }
        return Response(data)
