"""
Integrations UI Views
"""

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.shortcuts import render, redirect
from django.contrib import messages
from django.utils.translation import gettext_lazy as _

from .models import SurveyTemplateMapping
from .serializers import SurveyTemplateMappingSerializer


class SurveyTemplateMappingViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing survey template mappings.

    Provides CRUD operations for mapping patient types to survey templates.
    """

    queryset = SurveyTemplateMapping.objects.select_related("hospital", "survey_template").all()
    serializer_class = SurveyTemplateMappingSerializer
    filterset_fields = ["hospital", "patient_type", "is_active"]
    search_fields = ["hospital__name", "patient_type", "survey_template__name"]
    ordering_fields = ["hospital", "patient_type", "is_active"]
    ordering = ["hospital", "patient_type", "is_active"]

    def get_queryset(self):
        """
        Filter mappings by user's accessible hospitals.
        """
        queryset = super().get_queryset()
        user = self.request.user

        # Superusers see all mappings
        if user.is_superuser:
            return queryset

        # PX Admins filter by session hospital
        if user.is_px_admin():
            tenant_hospital = getattr(self.request, "tenant_hospital", None)
            if tenant_hospital:
                return queryset.filter(hospital=tenant_hospital)
            # If no session hospital, show all (for management)
            return queryset

        # Hospital users filter by their assigned hospital
        if hasattr(user, "hospital") and user.hospital:
            return queryset.filter(hospital=user.hospital)

        # User without hospital assignment - no access
        return queryset.none()

    def perform_create(self, serializer):
        """Add created_by information"""
        serializer.save()

    @action(detail=False, methods=["get"])
    def by_hospital(self, request):
        """
        Get all mappings for a specific hospital.

        Query param: hospital_id
        """
        hospital_id = request.query_params.get("hospital_id")

        if not hospital_id:
            return Response({"error": "hospital_id parameter is required"}, status=status.HTTP_400_BAD_REQUEST)

        mappings = self.get_queryset().filter(hospital_id=hospital_id)
        serializer = self.get_serializer(mappings, many=True)

        return Response(serializer.data)

    @action(detail=False, methods=["get"])
    def by_patient_type(self, request):
        """
        Get mapping for a specific patient type and hospital.

        Query params: hospital_id, patient_type_code
        """
        hospital_id = request.query_params.get("hospital_id")
        patient_type_code = request.query_params.get("patient_type_code")

        if not hospital_id or not patient_type_code:
            return Response(
                {"error": "hospital_id and patient_type_code parameters are required"},
                status=status.HTTP_400_BAD_REQUEST,
            )

        mapping = SurveyTemplateMapping.get_template_for_patient_type(patient_type_code, hospital_id)

        if not mapping:
            return Response({"error": "No mapping found"}, status=status.HTTP_404_NOT_FOUND)

        serializer = self.get_serializer(mapping)
        return Response(serializer.data)

    @action(detail=False, methods=["post"])
    def bulk_create(self, request):
        """
        Create multiple mappings at once.

        Expects: {
            "mappings": [
                {
                    "hospital": 1,
                    "patient_type_code": "1",
                    "patient_type_name": "Inpatient",
                    "survey_template": 1,
                    "priority": 1
                },
                ...
            ]
        }
        """
        mappings_data = request.data.get("mappings", [])

        if not mappings_data:
            return Response({"error": "mappings array is required"}, status=status.HTTP_400_BAD_REQUEST)

        created_mappings = []
        for mapping_data in mappings_data:
            serializer = self.get_serializer(data=mapping_data)
            if serializer.is_valid():
                serializer.save()
                created_mappings.append(serializer.data)

        return Response(
            {"created": len(created_mappings), "mappings": created_mappings}, status=status.HTTP_201_CREATED
        )


def survey_mapping_settings(request):
    """
    Survey mapping settings page.

    Allows administrators to configure which survey templates
    are sent for each patient type at each hospital.
    """
    from apps.organizations.models import Hospital

    user = request.user

    # Determine user's hospital context
    user_hospital = None
    if user.is_px_admin():
        user_hospital = getattr(request, "tenant_hospital", None)
    elif user.hospital:
        user_hospital = user.hospital

    # Get user's accessible hospitals based on role
    if user.is_superuser:
        # Superusers can see all hospitals
        hospitals = Hospital.objects.filter(status="active")
    elif user.is_px_admin():
        # PX Admins see all active hospitals for the dropdown
        # They use session-based hospital selection (request.tenant_hospital)
        hospitals = Hospital.objects.filter(status="active")
    elif user.hospital:
        # Regular users can only see their assigned hospital
        hospitals = Hospital.objects.filter(id=user.hospital.id)
    else:
        # User without hospital assignment - no access
        hospitals = Hospital.objects.none()

    # Get all mappings based on user role
    if user.is_superuser:
        # Superusers see all mappings
        mappings = SurveyTemplateMapping.objects.select_related("hospital", "survey_template").all()
    elif user.is_px_admin():
        # PX Admins filter by session hospital
        if user_hospital:
            mappings = SurveyTemplateMapping.objects.filter(hospital=user_hospital).select_related(
                "hospital", "survey_template"
            )
        else:
            # No session hospital - show all (for management)
            mappings = SurveyTemplateMapping.objects.select_related("hospital", "survey_template").all()
    else:
        # Regular users see only their hospital's mappings
        mappings = SurveyTemplateMapping.objects.filter(hospital__in=hospitals).select_related(
            "hospital", "survey_template"
        )

    # Group mappings by hospital
    mappings_by_hospital = {}
    for mapping in mappings:
        # Skip mappings with missing hospital (orphaned records)
        if mapping.hospital is None:
            continue
        hospital_name = mapping.hospital.name
        if hospital_name not in mappings_by_hospital:
            mappings_by_hospital[hospital_name] = []
        mappings_by_hospital[hospital_name].append(mapping)

    context = {
        "hospitals": hospitals,
        "mappings": mappings,
        "mappings_by_hospital": mappings_by_hospital,
        "page_title": _("Survey Template Mappings"),
        "user_hospital": user_hospital,
    }

    return render(request, "integrations/survey_mapping_settings.html", context)
