"""
Projects admin
"""
from django.contrib import admin

from .models import QIProject, QIProjectTask


class QIProjectTaskInline(admin.TabularInline):
    """Inline admin for QI project tasks"""
    model = QIProjectTask
    extra = 1
    fields = ['order', 'title', 'assigned_to', 'status', 'due_date']
    ordering = ['order']


@admin.register(QIProject)
class QIProjectAdmin(admin.ModelAdmin):
    """QI Project admin"""
    list_display = [
        'name', 'hospital', 'department', 'project_lead',
        'status', 'start_date', 'target_completion_date'
    ]
    list_filter = ['status', 'hospital', 'department', 'start_date']
    search_fields = ['name', 'name_ar', 'description']
    ordering = ['-created_at']
    inlines = [QIProjectTaskInline]
    filter_horizontal = ['team_members', 'related_actions']
    
    fieldsets = (
        (None, {
            'fields': ('name', 'name_ar', 'description')
        }),
        ('Organization', {
            'fields': ('hospital', 'department')
        }),
        ('Team', {
            'fields': ('project_lead', 'team_members')
        }),
        ('Status & Dates', {
            'fields': ('status', 'start_date', 'target_completion_date', 'actual_completion_date')
        }),
        ('Related Actions', {
            'fields': ('related_actions',),
            'classes': ('collapse',)
        }),
        ('Outcomes', {
            'fields': ('outcome_description', 'success_metrics'),
            'classes': ('collapse',)
        }),
        ('Metadata', {
            'fields': ('metadata', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at']
    
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related('hospital', 'department', 'project_lead')


@admin.register(QIProjectTask)
class QIProjectTaskAdmin(admin.ModelAdmin):
    """QI Project task admin"""
    list_display = [
        'project', 'title', 'assigned_to', 'status',
        'due_date', 'completed_date'
    ]
    list_filter = ['status', 'project', 'due_date']
    search_fields = ['title', 'description', 'project__name']
    ordering = ['project', 'order']
    
    fieldsets = (
        (None, {
            'fields': ('project', 'title', 'description', 'order')
        }),
        ('Assignment', {
            'fields': ('assigned_to',)
        }),
        ('Status & Dates', {
            'fields': ('status', 'due_date', 'completed_date')
        }),
        ('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('project', 'assigned_to')
