from pathlib import Path

from django.http import FileResponse
from django.shortcuts import get_object_or_404
from rest_framework import permissions, status
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.accounts_rbac.models import User, UserSecurityEvent
from apps.accounts_rbac.serializers import UserProfileSerializer
from apps.accounts_rbac.services import (
    StaffCodeResetService,
    StaffProfileService,
    UserAccountService,
    UserAvatarService,
    UserSessionService,
)
from apps.hr.models import StaffProfileChangeRequest
from apps.hr.staff_services import StaffProfileChangeService
from apps.system_admin.models import SecurityLoginEvent


class ProfileMeView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        data = UserProfileSerializer(request.user).data
        emp = getattr(request.user, "staff_employee", None)
        if emp:
            data["personal_details"] = {
                "personal_address": emp.personal_address,
                "province": emp.province,
                "district": emp.district,
                "local_level": emp.local_level,
                "ward": emp.ward,
                "emergency_contact_name": emp.emergency_contact_name,
                "emergency_contact_phone": emp.emergency_contact_phone,
                "date_of_birth": emp.date_of_birth.isoformat() if emp.date_of_birth else None,
            }
            data["employment_readonly"] = {
                "employee_code": emp.employee_profile.employee_code,
                "company_name": emp.company.name,
                "branch_name": emp.branch.name if emp.branch else None,
                "department_name": emp.employee_profile.department.name if emp.employee_profile.department else None,
                "designation": emp.employee_profile.designation,
                "employment_type": emp.employment_type,
                "joining_date": emp.joining_date.isoformat() if emp.joining_date else None,
                "reporting_manager": emp.reporting_manager.employee_profile.full_name if emp.reporting_manager else None,
                "project_name": emp.employee_profile.project.name if emp.employee_profile.project else None,
                "status": emp.status,
            }
        return Response(data)

    def patch(self, request):
        changed = StaffProfileService.update_personal_details(
            user=request.user,
            data=request.data,
            ip_address=request.META.get("REMOTE_ADDR"),
        )
        return Response({"changed": changed, "profile": UserProfileSerializer(request.user).data})


class ProfileAvatarView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request):
        file_obj = request.FILES.get("file") or request.FILES.get("avatar")
        if not file_obj:
            return Response({"detail": "Image file is required."}, status=status.HTTP_400_BAD_REQUEST)
        try:
            av = UserAvatarService.upload_avatar(
                user=request.user,
                file_obj=file_obj,
                ip_address=request.META.get("REMOTE_ADDR"),
            )
            return Response(
                {
                    "avatar_url": f"/api/profile/avatar/{request.user.id}/",
                    "file_type": av.file_type,
                    "width": av.width,
                    "height": av.height,
                    "size_bytes": av.size_bytes,
                }
            )
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request):
        UserAvatarService.remove_avatar(user=request.user, ip_address=request.META.get("REMOTE_ADDR"))
        return Response(status=status.HTTP_204_NO_CONTENT)


class ProfileAvatarStreamView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, user_id):
        target = get_object_or_404(User, id=user_id)
        av = getattr(target, "avatar", None)
        if not av:
            return Response({"detail": "No avatar configured."}, status=status.HTTP_404_NOT_FOUND)
        use_thumb = request.query_params.get("thumb") == "1"
        path = Path(av.thumbnail_path if use_thumb else av.image_path)
        if not path.exists():
            return Response({"detail": "Avatar image not found."}, status=status.HTTP_404_NOT_FOUND)
        return FileResponse(path.open("rb"), content_type="image/webp")


class ProfileContactVerifyView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        try:
            res = StaffProfileService.request_contact_verification(
                user=request.user,
                channel=request.data.get("channel", "EMAIL"),
                new_contact=request.data.get("new_contact", ""),
                ip_address=request.META.get("REMOTE_ADDR"),
            )
            return Response(res)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class ProfileContactUpdateView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        try:
            res = StaffProfileService.verify_and_apply_contact(
                user=request.user,
                challenge_id=request.data.get("challenge_id", ""),
                verification_code=request.data.get("verification_code", ""),
                ip_address=request.META.get("REMOTE_ADDR"),
            )
            return Response(res)
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class ProfileChangePasswordView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        try:
            UserAccountService.change_password(
                user=request.user,
                current_password=request.data.get("current_password", ""),
                new_password=request.data.get("new_password", ""),
                ip_address=request.META.get("REMOTE_ADDR"),
            )
            return Response({"detail": "Password changed successfully."})
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class ProfileStaffCodeStatusView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        cred = getattr(request.user, "staff_credential", None)
        if not cred:
            return Response({"assigned": False, "masked_code": None})
        # Deliberately NEVER exposes plaintext code or hash
        return Response(
            {
                "assigned": True,
                "masked_code": "******",
                "code_login_enabled": cred.code_login_enabled,
                "code_changed_at": cred.code_changed_at.isoformat(),
                "code_expires_at": cred.code_expires_at.isoformat() if cred.code_expires_at else None,
                "failed_attempt_count": cred.failed_attempt_count,
                "last_code_login_at": cred.last_code_login_at.isoformat() if cred.last_code_login_at else None,
                "must_change_code": cred.must_change_code,
            }
        )


class ProfileChangeStaffCodeView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        try:
            StaffCodeResetService.self_change(
                user=request.user,
                new_code=request.data.get("new_code", ""),
                current_password=request.data.get("current_password", ""),
                current_code=request.data.get("current_code", ""),
                ip_address=request.META.get("REMOTE_ADDR"),
            )
            return Response({"detail": "6-digit staff login code updated.", "masked_code": "******"})
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class ProfileDisableStaffCodeView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        enabled = bool(request.data.get("enabled", False))
        try:
            return Response(
                StaffCodeResetService.toggle_code_login(
                    user=request.user,
                    enabled=enabled,
                    actor=request.user,
                    ip_address=request.META.get("REMOTE_ADDR"),
                )
            )
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class ProfileMySessionsView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        return Response(UserSessionService.list_my_sessions(request.user))


class ProfileRevokeSessionView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        try:
            UserSessionService.revoke_my_device(
                user=request.user,
                device_pk=request.data.get("device_id", ""),
                ip_address=request.META.get("REMOTE_ADDR"),
            )
            return Response({"detail": "Device session revoked."})
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)


class ProfileRevokeAllSessionsView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request):
        cnt = UserSessionService.revoke_all_sessions(
            user=request.user, actor=request.user, ip_address=request.META.get("REMOTE_ADDR")
        )
        return Response({"detail": f"Revoked {cnt} active device(s)."})


class ProfileLoginHistoryView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        sec_events = list(
            UserSecurityEvent.objects.filter(user=request.user)
            .values("id", "event_type", "status", "device_id", "ip_address", "details", "created_at")[:50]
        )
        login_events = list(
            SecurityLoginEvent.objects.filter(user=request.user)
            .values("id", "event_type", "ip_address", "device_id", "failure_reason", "created_at")[:50]
        )
        return Response({"security_events": sec_events, "login_events": login_events})


class ProfileChangeRequestView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        qs = StaffProfileChangeRequest.objects.filter(user=request.user).values(
            "id", "field_name", "old_value", "requested_value", "reason", "approval_status", "review_note", "created_at"
        )
        return Response(list(qs[:30]))

    def post(self, request):
        try:
            req = StaffProfileChangeService.submit_request(
                user=request.user,
                field_name=request.data.get("field_name", ""),
                requested_value=request.data.get("requested_value", ""),
                reason=request.data.get("reason", ""),
            )
            return Response(
                {
                    "id": str(req.id),
                    "field_name": req.field_name,
                    "approval_status": req.approval_status,
                },
                status=status.HTTP_201_CREATED,
            )
        except ValueError as exc:
            return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)

