"""
Journeys admin
"""
from django.contrib import admin

from .models import (
    PatientJourneyInstance,
    PatientJourneyStageInstance,
    PatientJourneyStageTemplate,
    PatientJourneyTemplate,
)


class PatientJourneyStageTemplateInline(admin.TabularInline):
    """Inline admin for journey stage templates"""
    model = PatientJourneyStageTemplate
    extra = 1
    fields = [
        'order', 'name', 'code', 'trigger_event_code',
        'survey_template', 'is_optional', 'is_active'
    ]
    ordering = ['order']


@admin.register(PatientJourneyTemplate)
class PatientJourneyTemplateAdmin(admin.ModelAdmin):
    """Journey template admin"""
    list_display = ['name', 'journey_type', 'hospital', 'is_active', 'is_default', 'created_at']
    list_filter = ['journey_type', 'is_active', 'is_default', 'hospital']
    search_fields = ['name', 'name_ar', 'description']
    ordering = ['hospital', 'journey_type', 'name']
    inlines = [PatientJourneyStageTemplateInline]

    fieldsets = (
        (None, {'fields': ('name', 'name_ar', 'journey_type', 'description')}),
        ('Configuration', {'fields': ('hospital', 'is_active', 'is_default')}),
        ('Post-Discharge Survey', {
            'fields': ('send_post_discharge_survey', 'post_discharge_survey_delay_hours')
        }),
        ('Metadata', {'fields': ('created_at', 'updated_at')}),
    )

    readonly_fields = ['created_at', 'updated_at']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('hospital')


@admin.register(PatientJourneyStageTemplate)
class PatientJourneyStageTemplateAdmin(admin.ModelAdmin):
    """Journey stage template admin"""
    list_display = [
        'name', 'journey_template', 'order', 'trigger_event_code',
        'is_optional', 'is_active'
    ]
    list_filter = ['journey_template__journey_type', 'is_optional', 'is_active']
    search_fields = ['name', 'name_ar', 'code', 'trigger_event_code']
    ordering = ['journey_template', 'order']

    fieldsets = (
        (None, {'fields': ('journey_template', 'name', 'name_ar', 'code', 'order')}),
        ('Event Trigger', {'fields': ('trigger_event_code',)}),
        ('Survey Configuration', {
            'fields': ('survey_template',)
        }),
        ('Configuration', {
            'fields': ('is_optional', 'is_active')
        }),
        ('Metadata', {'fields': ('created_at', 'updated_at')}),
    )

    readonly_fields = ['created_at', 'updated_at']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('journey_template', 'survey_template')


class PatientJourneyStageInstanceInline(admin.TabularInline):
    """Inline admin for journey stage instances"""
    model = PatientJourneyStageInstance
    extra = 0
    fields = [
        'stage_template', 'status', 'completed_at',
        'staff', 'department'
    ]
    readonly_fields = ['stage_template', 'completed_at']
    ordering = ['stage_template__order']

    def has_add_permission(self, request, obj=None):
        return False


@admin.register(PatientJourneyInstance)
class PatientJourneyInstanceAdmin(admin.ModelAdmin):
    """Journey instance admin"""
    list_display = [
        'encounter_id', 'patient', 'journey_template', 'hospital',
        'status', 'get_completion_percentage', 'started_at'
    ]
    list_filter = ['status', 'journey_template__journey_type', 'hospital', 'started_at']
    search_fields = ['encounter_id', 'patient__mrn', 'patient__first_name', 'patient__last_name']
    ordering = ['-started_at']
    inlines = [PatientJourneyStageInstanceInline]

    fieldsets = (
        (None, {
            'fields': ('journey_template', 'patient', 'encounter_id')
        }),
        ('Organization', {
            'fields': ('hospital', 'department')
        }),
        ('Status', {
            'fields': ('status', 'started_at', 'completed_at')
        }),
        ('Metadata', {
            'fields': ('metadata', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    readonly_fields = ['started_at', 'completed_at', 'created_at', 'updated_at']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related(
            'journey_template', 'patient', 'hospital', 'department'
        ).prefetch_related('stage_instances')

    def get_completion_percentage(self, obj):
        """Display completion percentage"""
        return f"{obj.get_completion_percentage()}%"
    get_completion_percentage.short_description = 'Completion'


@admin.register(PatientJourneyStageInstance)
class PatientJourneyStageInstanceAdmin(admin.ModelAdmin):
    """Journey stage instance admin"""
    list_display = [
        'journey_instance', 'stage_template', 'status',
        'completed_at', 'staff'
    ]
    list_filter = ['status', 'stage_template__journey_template__journey_type', 'completed_at']
    search_fields = [
        'journey_instance__encounter_id',
        'journey_instance__patient__mrn',
        'stage_template__name'
    ]
    ordering = ['journey_instance', 'stage_template__order']

    fieldsets = (
        (None, {
            'fields': ('journey_instance', 'stage_template', 'status')
        }),
        ('Completion Details', {
            'fields': ('completed_at', 'staff', 'department')
        }),
        ('Metadata', {
            'fields': ('metadata', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    readonly_fields = ['completed_at', 'created_at', 'updated_at']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related(
            'journey_instance',
            'stage_template',
            'staff',
            'department'
        )
