from django.shortcuts import render

# Create your views here.

# ============================================================
# ADDITIVE: Company (Admin) login / logout + auth log list
# ============================================================

from django.utils import timezone
from django.db.models import Sum, Count

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status as http_status
from rest_framework.exceptions import PermissionDenied
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.exceptions import TokenError

from rest_framework.viewsets import ModelViewSet
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser

from .models import company_details, AuthLog, log_auth_event, blacklist_token, Holiday
from .serializers import (
    AuthLogSerializer,
    CompanyDetailsSerializer,
    CompanyProfileSerializer,
    HolidaySerializer,
)
from Employee.employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    IsAdminOrHR,
    resolve_company_for_user,
)
from .company_authentication import (
    CompanyJWTAuthentication,
    IsCompanyAuthenticated,
)


# ============================================================
# COMPANY ADMIN LOGIN
# ============================================================

class CompanyAdminLoginView(APIView):
    """
    POST /company/auth/login/

    body:
        {
            "email": "owner@example.com",
            "password": "xxxxxxxx"
        }

    Issues a JWT (type="company") for the tenant/company
    account and writes one AuthLog row per attempt
    (success and failure both logged).
    """

    authentication_classes = []
    permission_classes = []

    def post(self, request):

        email = request.data.get("email")
        password = request.data.get("password")

        if not email or not password:

            log_auth_event(
                actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                reason="Missing email or password",
            )

            return Response({
                "status": "error",
                "code": "missing_fields",
                "message": "Email and password are required.",
                "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        try:

            company = company_details.objects.get(email=email)

        except company_details.DoesNotExist:

            log_auth_event(
                actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                reason="Company not found",
            )

            return Response({
                "status": "error",
                "code": "invalid_credentials",
                "message": "Invalid email or password.",
                "data": None,
            }, status=http_status.HTTP_401_UNAUTHORIZED)

        if company.password != password:

            log_auth_event(
                actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=company.company_id,
                company=company,
                reason="Incorrect password",
            )

            return Response({
                "status": "error",
                "code": "invalid_credentials",
                "message": "Invalid email or password.",
                "data": None,
            }, status=http_status.HTTP_401_UNAUTHORIZED)

        if not company.status:

            log_auth_event(
                actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=company.company_id,
                company=company,
                reason="Company inactive",
            )

            return Response({
                "status": "error",
                "code": "company_disabled",
                "message": "Company account is inactive.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        if not company.is_verified:

            log_auth_event(
                actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
                action=AuthLog.ACTION_LOGIN,
                status=AuthLog.STATUS_FAILED,
                request=request,
                identifier=email,
                actor_id=company.company_id,
                company=company,
                reason="Company not verified",
            )

            return Response({
                "status": "error",
                "code": "company_not_verified",
                "message": "Company account is not verified.",
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        refresh = RefreshToken()
        refresh["type"] = "company"
        refresh["user_id"] = company.company_id
        refresh["email"] = company.email

        log_auth_event(
            actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
            action=AuthLog.ACTION_LOGIN,
            status=AuthLog.STATUS_SUCCESS,
            request=request,
            identifier=email,
            actor_id=company.company_id,
            company=company,
        )

        return Response({
            "status": "success",
            "code": "login_success",
            "message": "Login successful.",
            "data": {
                "access": str(refresh.access_token),
                "refresh": str(refresh),
                "company_id": company.company_id,
                "email": company.email,
                "company_name": company.Registered_Company_Name,
                # ADDITIVE: frontend can redirect here right after login
                "redirect_url": "/company/dashboard/",
            },
        }, status=http_status.HTTP_200_OK)


# ============================================================
# COMPANY ADMIN LOGOUT
# ============================================================

class CompanyAdminLogoutView(APIView):
    """
    POST /company/auth/logout/

    body:
        { "refresh": "<refresh_token>" }

    Requires a valid company access token (Authorization:
    Bearer <access>). Blacklists the refresh token so it
    can't be reused, and logs the logout.
    """

    authentication_classes = [CompanyJWTAuthentication]
    permission_classes = [IsCompanyAuthenticated]

    def post(self, request):

        company = request.user
        refresh_token = request.data.get("refresh")

        if not refresh_token:

            return Response({
                "status": "error",
                "code": "missing_refresh_token",
                "message": "Refresh token is required.",
                "data": None,
            }, status=http_status.HTTP_400_BAD_REQUEST)

        try:

            token = RefreshToken(refresh_token)
            blacklist_token(token)

        except TokenError:
            # Already invalid/expired/blacklisted - still
            # treat the logout as successful client-side.
            pass

        log_auth_event(
            actor_type=AuthLog.ACTOR_COMPANY_ADMIN,
            action=AuthLog.ACTION_LOGOUT,
            status=AuthLog.STATUS_SUCCESS,
            request=request,
            identifier=company.email,
            actor_id=company.company_id,
            company=company,
        )

        return Response({
            "status": "success",
            "code": "logout_success",
            "message": "Logged out successfully.",
            "data": None,
        }, status=http_status.HTTP_200_OK)


# ============================================================
# COMPANY AUTH LOG LIST (this company only)
# ============================================================

class CompanyAuthLogListView(APIView):
    """
    GET /company/auth/logs/

    Returns login/logout history for the authenticated
    company + its own employees, newest first.
    Optional query params: ?action=LOGIN|LOGOUT
                            ?status=SUCCESS|FAILED
                            ?actor_type=COMPANY_ADMIN|EMPLOYEE
    """

    authentication_classes = [CompanyJWTAuthentication]
    permission_classes = [IsCompanyAuthenticated]

    def get(self, request):

        company = request.user

        logs = AuthLog.objects.filter(company=company)

        action = request.query_params.get("action")
        if action:
            logs = logs.filter(action=action.upper())

        req_status = request.query_params.get("status")
        if req_status:
            logs = logs.filter(status=req_status.upper())

        actor_type = request.query_params.get("actor_type")
        if actor_type:
            logs = logs.filter(actor_type=actor_type.upper())

        logs = logs[:200]

        serializer = AuthLogSerializer(logs, many=True)

        return Response({
            "status": "success",
            "code": "auth_logs",
            "message": "Auth logs fetched successfully.",
            "data": serializer.data,
        }, status=http_status.HTTP_200_OK)


# ============================================================
# ADDITIVE: Company Profile (view / update own company_details)
# GET   -> view own profile
# PUT   -> full update
# PATCH -> partial update
# (Create = normal signup flow, Delete intentionally not
# exposed here - deactivating a company is a SuperAdmin action)
# ============================================================

class CompanyProfileView(APIView):
    """
    GET    /company/profile/
    PUT    /company/profile/
    PATCH  /company/profile/

    Company Admin: always. Employees / HR: only when their role has
    can_view_company (read) or can_edit_company / can_manage_company
    (write) ticked - off by default.

    Login identifiers (email, contact_no) and platform flags
    (status, is_verified, company_status) are read-only here, and
    password / api_key / verification_code are never returned.
    Company-isolated: the company always comes from the token.
    """

    authentication_classes = [AdminOrEmployeeJWTAuthentication]
    permission_classes = [IsAdminOrHR]
    permission_module = "company"
    permission_write_action = "edit"
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def get(self, request):

        try:

            company = resolve_company_for_user(request.user)

            serializer = CompanyProfileSerializer(
                company, context={"request": request}
            )

            return Response({
                "status": "success",
                "code": "company_profile",
                "message": "Company profile fetched successfully.",
                "data": serializer.data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not fetch company profile: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)

    def put(self, request):
        return self._update(request, partial=False)

    def patch(self, request):
        return self._update(request, partial=True)

    def _update(self, request, partial):

        try:

            company = resolve_company_for_user(request.user)

            serializer = CompanyProfileSerializer(
                company,
                data=request.data,
                partial=partial,
                context={"request": request},
            )

            if not serializer.is_valid():

                return Response({
                    "status": "error",
                    "code": "validation_error",
                    "message": "Invalid company profile data.",
                    "data": serializer.errors,
                }, status=http_status.HTTP_400_BAD_REQUEST)

            serializer.save()

            return Response({
                "status": "success",
                "code": "company_profile_updated",
                "message": "Company profile updated successfully.",
                "data": serializer.data,
            }, status=http_status.HTTP_200_OK)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not update company profile: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)


# ============================================================
# ADDITIVE: Company Holiday CRUD (Admin / HR manage the
# holiday list; dashboards read from it - see
# CompanyDashboardView / Employee.views.EmployeeDashboardView)
# ============================================================

class HolidayViewSet(ModelViewSet):
    """
    Full CRUD for the company holiday list.

    GET    /api/holidays/         list
    POST   /api/holidays/         create
    GET    /api/holidays/<id>/    retrieve
    PUT    /api/holidays/<id>/    update
    PATCH  /api/holidays/<id>/    partial update
    DELETE /api/holidays/<id>/    delete

    Company Admin or HR-role employee only (same
    AdminOrEmployeeJWTAuthentication / IsAdminOrHR pair used by
    EmployeeViewSet / EmployeeRoleViewSet). Company-isolated: a
    mismatched <id> from another company 404s instead of leaking
    data.
    """

    serializer_class = HolidaySerializer
    ordering = ["date"]

    def get_authenticators(self):
        from Employee.employee_crud_permissions import (
            AdminOrEmployeeJWTAuthentication,
        )
        return [AdminOrEmployeeJWTAuthentication()]

    def get_permissions(self):
        from Employee.employee_crud_permissions import IsAdminOrHR
        return [IsAdminOrHR()]

    def get_company(self):

        from Employee.employee_crud_permissions import resolve_company_for_user

        company = resolve_company_for_user(self.request.user)

        if company is None:
            raise PermissionDenied(
                "Unable to resolve your company. Access denied."
            )

        return company

    def get_queryset(self):

        qs = Holiday.objects.filter(company=self.get_company())

        year = self.request.query_params.get("year")
        if year:
            qs = qs.filter(date__year=year)

        month = self.request.query_params.get("month")
        if month:
            qs = qs.filter(date__month=month)

        return qs.order_by("date")

    def perform_create(self, serializer):

        serializer.save(
            company=self.get_company(),
            source="manual"
        )


    def perform_update(self, serializer):

        serializer.save(
            company=self.get_company(),
            source="manual"
        )

# ============================================================
# ADDITIVE: Company / HR Dashboard
# Viewable by BOTH Company Admin and HR-role Employees, reusing
# the existing AdminOrEmployeeJWTAuthentication / IsAdminOrHR
# pair from Employee.employee_crud_permissions (no duplicate
# auth logic - see that file for why the wrapper is needed).
# ============================================================

class CompanyDashboardView(APIView):
    """
    GET /company/dashboard/

    Company-wide HR dashboard: headcount, this month's new
    joiners / birthdays / work anniversaries, today's
    attendance breakdown and this month's payroll summary.
    """

    def get_authenticators(self):
        from Employee.employee_crud_permissions import (
            AdminOrEmployeeJWTAuthentication,
        )
        return [AdminOrEmployeeJWTAuthentication()]

    def get_permissions(self):
        from Employee.employee_crud_permissions import IsAdminOrHR
        return [IsAdminOrHR()]

    def get(self, request):

        try:

            from Employee.employee_crud_permissions import (
                resolve_company_for_user,
            )
            from Employee.models import (
                EmployeeDT,
                EMP_check_in_check_out,
                AttendanceEmp,
                Payroll,
            )

            company = resolve_company_for_user(request.user)

            if company is None:
                raise PermissionDenied(
                    "Unable to resolve your company. Access denied."
                )

            today = timezone.localdate()

            # ---------------- HEADCOUNT ----------------
            total_employees = EmployeeDT.objects.filter(
                company=company,
                Employee_Status__iexact="Activate",
                is_active=True,
            ).count()

            active_employees = EmployeeDT.objects.filter(
                company=company,
                Employee_Status__iexact="Activate",
                is_active=True
            ).count()

            # ---------------- NEW JOINING (this month) ----------------
            new_joining = list(
                EmployeeDT.objects.filter(
                    company=company,
                    Employee_Status__iexact="Activate",
                    is_active=True,
                    Date_of_Joining__year=today.year,
                    Date_of_Joining__month=today.month,
                ).values("employee_code", "name", "Date_of_Joining", "Department", "department__name")
            )

            # ---------------- BIRTHDAYS (this month) ----------------
            birthdays_this_month = list(
                EmployeeDT.objects.filter(
                    company=company,
                    Employee_Status__iexact="Activate",
                    is_active=True,
                    Date_of_Birth__month=today.month,
                ).values("employee_code", "name", "Date_of_Birth", "Department", "department__name")
            )

            # ---------------- WORK ANNIVERSARIES (this month) ----------------
            work_anniversary = list(
                EmployeeDT.objects.filter(
                    company=company,
                    Employee_Status__iexact="Activate",
                    is_active=True,
                    Date_of_Joining__month=today.month,
                    Date_of_Joining__year__lt=today.year,
                ).values("employee_code", "name", "Date_of_Joining", "Department", "department__name")
            )

            # ---------------- TODAY'S CHECK-IN / CHECK-OUT ----------------
            # "today" counts: how many check-in/out records touch today
            checked_in_today = EMP_check_in_check_out.objects.filter(
                company=company, login_date=today
            ).count()

            checked_out_today = EMP_check_in_check_out.objects.filter(
                company=company, logout_date=today
            ).count()

            not_checked_in_today = max(
                total_employees - checked_in_today, 0
            )

            # "live" counts: EmployeeDT.check_st right now (same field/
            # semantics as the legacy CheckIn_Emp_count / CheckOut_Emp_count
            # views - who is CURRENTLY checked in vs not, this instant)
            live_checked_in = EmployeeDT.objects.filter(
                company=company,
                Employee_Status__iexact="Activate",
                is_active=True, check_st="check_in"
            ).count()

            live_checked_out = EmployeeDT.objects.filter(
                company=company,
                Employee_Status__iexact="Activate",
                is_active=True, check_st__isnull=True
            ).count()

            # ---------------- TODAY'S ATTENDANCE BREAKDOWN ----------------
            attendance_today_qs = AttendanceEmp.objects.filter(
                company=company, date=today
            ).values("status").annotate(count=Count("id"))

            attendance_today = {
                row["status"] or "Unmarked": row["count"]
                for row in attendance_today_qs
            }

            # ---------------- THIS MONTH'S PAYROLL SUMMARY ----------------
            payroll_qs = Payroll.objects.filter(
                company=company,
                month=today.month,
                year=today.year,
            )

            paid_summary = payroll_qs.filter(status="Paid").aggregate(
                total=Sum("amount_paid"), count=Count("id")
            )

            unpaid_summary = payroll_qs.filter(status="Unpaid").aggregate(
                total=Sum("net_salary"), count=Count("id")
            )

            # ---------------- HOLIDAYS ----------------
            # Every active holiday of the current year: manually added
            # + imported from the holiday library (see `source`).
            all_holidays = list(
                Holiday.objects.filter(
                    company=company,
                    is_active=True,
                ).order_by("date").values(
                    "id", "name", "date", "holiday_type", "source"
                )
            )

            holidays_this_year = [
                h for h in all_holidays if h["date"].year == today.year
            ]

            holidays_this_month = [
                h for h in holidays_this_year
                if h["date"].month == today.month
            ]

            # Everything from today onwards, across years.
            upcoming_holidays = [
                h for h in all_holidays if h["date"] >= today
            ]

            data = {
                "company_id": company.company_id,
                "company_name": company.Registered_Company_Name,
                "total_employees": total_employees,
                "active_employees": active_employees,
                "new_joining": new_joining,
                "birthdays_this_month": birthdays_this_month,
                "work_anniversary": work_anniversary,
                "holidays_this_month": holidays_this_month,
                "upcoming_holidays": upcoming_holidays,
                "holidays_this_year": holidays_this_year,
                "all_holidays": all_holidays,
                "today": {
                    "checked_in": checked_in_today,
                    "checked_out": checked_out_today,
                    "not_checked_in": not_checked_in_today,
                    "live_checked_in": live_checked_in,
                    "live_checked_out": live_checked_out,
                    "attendance_breakdown": attendance_today,
                },
                "payroll_this_month": {
                    "paid_amount": paid_summary["total"] or 0,
                    "paid_count": paid_summary["count"] or 0,
                    "unpaid_amount": unpaid_summary["total"] or 0,
                    "unpaid_count": unpaid_summary["count"] or 0,
                },
            }

            return Response({
                "status": "success",
                "code": "company_dashboard",
                "message": "Dashboard data fetched successfully.",
                "data": data,
            }, status=http_status.HTTP_200_OK)

        except PermissionDenied as exc:

            return Response({
                "status": "error",
                "code": "permission_denied",
                "message": str(exc),
                "data": None,
            }, status=http_status.HTTP_403_FORBIDDEN)

        except Exception as exc:

            return Response({
                "status": "error",
                "code": "server_error",
                "message": f"Could not load dashboard: {exc}",
                "data": None,
            }, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
            
            