from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from apps.jobs.models import JobDescription, JDRecruiterAssignment
from apps.clients.models import Client
from core.responses import success_response

User = get_user_model()


class DashboardStatsView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        total_users = User.objects.count()
        roles = Group.objects.count()
        job_descriptions = JobDescription.objects.count()
        clients = Client.objects.count()
        
        # total recruiters (role = 'RECRUITER')
        total_recruiters = User.objects.filter(role="RECRUITER").count()
        
        # assigned recruiters (recruiters currently assigned to at least one JD)
        assigned_recruiters = User.objects.filter(
            role="RECRUITER", 
            jd_assignments__isnull=False
        ).distinct().count()

        return success_response({
            "total_users": total_users,
            "roles": roles,
            "job_descriptions": job_descriptions,
            "clients": clients,
            "total_recruiters": total_recruiters,
            "assigned_recruiters": assigned_recruiters
        })


class TotalRecruitersView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        recruiters = User.objects.filter(role="RECRUITER").order_by("-date_joined")
        # Dashboard drill-down: "Assigned Recruiters" card narrows to exactly
        # the recruiters assigned to a JD *created by* the current user — the
        # same population the Project Manager dashboard's count is built from
        # (apps.dashboard.pm_views: JDRecruiterAssignment scoped to job_ids
        # owned by request.user), so the card's number always equals the
        # number of rows shown here.
        owner_param = (request.query_params.get("owner") or "").strip().lower()
        if owner_param == "me":
            my_job_ids = JobDescription.objects.filter(created_by=request.user).values_list("id", flat=True)
            recruiters = recruiters.filter(jd_assignments__jd_id__in=my_job_ids).distinct()
        data = []
        for r in recruiters:
            total_assigned = r.jd_assignments.count()
            total_active = r.jd_assignments.filter(jd__status="Published").count()
            total_candidates = r.candidates_created.count()
            
            data.append({
                "id": r.id,
                "employee_id": r.employee_id or "—",
                "full_name": r.full_name or r.email.split("@")[0],
                "email": r.email,
                "phone": r.phone or "—",
                "department": r.department or "—",
                "total_assigned_jds": total_assigned,
                "total_active_jds": total_active,
                "total_candidates_submitted": total_candidates,
                "status": "Active" if r.is_active else "Inactive",
                "created_date": r.date_joined.isoformat() if r.date_joined else None,
            })
        return success_response(data)


class AssignedRecruitersView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        recruiters = User.objects.filter(
            role="RECRUITER", 
            jd_assignments__isnull=False
        ).distinct().order_by("-date_joined")
        
        data = []
        for r in recruiters:
            assignments = r.jd_assignments.select_related("jd").all()
            assigned_jd_names = [a.jd.title for a in assignments if a.jd]
            assigned_jds_count = len(assigned_jd_names)
            open_jds = sum(1 for a in assignments if a.jd and a.jd.status == "Published")
            closed_jds = sum(1 for a in assignments if a.jd and a.jd.status == "Closed")
            
            # last assigned date
            last_assigned = assignments.order_by("-assigned_at").first()
            last_assigned_date = last_assigned.assigned_at.isoformat() if last_assigned else None

            data.append({
                "id": r.id,
                "full_name": r.full_name or r.email.split("@")[0],
                "employee_id": r.employee_id or "—",
                "email": r.email,
                "department": r.department or "—",
                "assigned_jds_count": assigned_jds_count,
                "assigned_jd_names": ", ".join(assigned_jd_names) if assigned_jd_names else "—",
                "open_jds": open_jds,
                "closed_jds": closed_jds,
                "last_assigned_date": last_assigned_date,
                "status": "Active" if r.is_active else "Inactive",
            })
        return success_response(data)


class RecruiterDetailView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        try:
            r = User.objects.get(pk=pk, role="RECRUITER")
        except User.DoesNotExist:
            return Response({"message": "Recruiter not found"}, status=404)
            
        info = {
            "id": r.id,
            "full_name": r.full_name or r.email.split("@")[0],
            "employee_id": r.employee_id or "—",
            "email": r.email,
            "phone": r.phone or "—",
            "department": r.department or "—",
        }
        
        assignments = r.jd_assignments.select_related("jd", "jd__client").all()
        jds = []
        for a in assignments:
            jd = a.jd
            if not jd:
                continue
            
            from apps.pipeline.models import JobApplication
            candidates_count = JobApplication.objects.filter(job=jd, created_by=r).count()

            jds.append({
                "jd_id": jd.id,
                "job_title": jd.title,
                "client": jd.client.name if jd.client else "Internal Job",
                "priority": jd.priority or "Medium",
                "status": jd.status,
                "assigned_date": a.assigned_at.isoformat() if a.assigned_at else None,
                "total_candidates": candidates_count,
            })
            
        return success_response({
            "recruiter": info,
            "assigned_jds": jds
        })
