from django.contrib import admin

from .models import ApplicationEvent, ApplicationNote, Interview


class ApplicationNoteInline(admin.TabularInline):
    model = ApplicationNote
    extra = 0
    fields = ('author', 'body', 'created_at')
    readonly_fields = ('created_at',)
    raw_id_fields = ('author',)
    ordering = ('-created_at',)


class InterviewInline(admin.TabularInline):
    model = Interview
    extra = 0
    fields = (
        'scheduled_at',
        'status',
        'location',
        'meeting_url',
        'notes',
        'created_by',
    )
    raw_id_fields = ('created_by',)
    ordering = ('scheduled_at',)


class ApplicationEventInline(admin.TabularInline):
    model = ApplicationEvent
    extra = 0
    fields = ('event_type', 'actor', 'old_value', 'new_value', 'message', 'created_at')
    readonly_fields = ('event_type', 'actor', 'old_value', 'new_value', 'message', 'created_at')
    can_delete = False
    ordering = ('-created_at',)

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


@admin.register(ApplicationNote)
class ApplicationNoteAdmin(admin.ModelAdmin):
    list_display = ('application', 'author', 'body_preview', 'created_at')
    list_filter = ('created_at',)
    search_fields = (
        'body',
        'application__job__title',
        'application__applicant__email',
        'application__applicant__username',
    )
    raw_id_fields = ('application', 'author')
    readonly_fields = ('created_at',)
    ordering = ('-created_at',)

    @admin.display(description='Note')
    def body_preview(self, obj):
        return obj.body[:80] + ('…' if len(obj.body) > 80 else '')


@admin.register(ApplicationEvent)
class ApplicationEventAdmin(admin.ModelAdmin):
    list_display = ('application', 'event_type', 'actor', 'new_value', 'created_at')
    list_filter = ('event_type', 'created_at')
    search_fields = (
        'message',
        'application__job__title',
        'application__applicant__email',
    )
    raw_id_fields = ('application', 'actor')
    readonly_fields = (
        'application',
        'actor',
        'event_type',
        'old_value',
        'new_value',
        'message',
        'created_at',
    )
    ordering = ('-created_at',)

    def has_add_permission(self, request):
        return False

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


@admin.register(Interview)
class InterviewAdmin(admin.ModelAdmin):
    list_display = (
        'application',
        'scheduled_at',
        'status',
        'location',
        'created_by',
        'created_at',
    )
    list_filter = ('status', 'scheduled_at')
    search_fields = (
        'application__job__title',
        'application__applicant__email',
        'location',
        'notes',
    )
    raw_id_fields = ('application', 'created_by')
    readonly_fields = ('created_at', 'updated_at')
    ordering = ('-scheduled_at',)
    date_hierarchy = 'scheduled_at'
