from django.contrib import admin
from django.utils import timezone

from .models import JobApplication, JobOffer


@admin.register(JobOffer)
class JobOfferAdmin(admin.ModelAdmin):
    list_display        = ['title', 'department', 'contract_type', 'location', 'status', 'application_deadline', 'created_at']
    list_filter         = ['status', 'department', 'contract_type', 'is_remote']
    search_fields       = ['title', 'location', 'description']
    prepopulated_fields = {'slug': ('title',)}
    readonly_fields     = ['published_at', 'created_at', 'updated_at']
    list_editable       = ['status']
    date_hierarchy      = 'created_at'
    actions             = ['publish_offers', 'close_offers']
    fieldsets = (
        ("Informations générales", {
            'fields': ('title', 'slug', 'department', 'contract_type', 'location', 'is_remote', 'salary_range')
        }),
        ("Contenu de l'offre", {
            'fields': ('description', 'requirements', 'nice_to_have')
        }),
        ('Publication', {
            'fields': ('status', 'application_deadline', 'published_at', 'created_at', 'updated_at')
        }),
    )

    @admin.action(description='Publier les offres sélectionnées')
    def publish_offers(self, request, queryset):
        queryset.update(status=JobOffer.Status.PUBLISHED, published_at=timezone.now())

    @admin.action(description='Fermer les offres sélectionnées')
    def close_offers(self, request, queryset):
        queryset.update(status=JobOffer.Status.CLOSED)


@admin.register(JobApplication)
class JobApplicationAdmin(admin.ModelAdmin):
    list_display  = ['full_name_col', 'email', 'job', 'status', 'applied_at']
    list_filter   = ['status', 'job__department', 'job']
    search_fields = ['first_name', 'last_name', 'email', 'job__title']
    readonly_fields = [
        'first_name', 'last_name', 'email', 'phone', 'linkedin_url',
        'cover_letter', 'cv_file', 'portfolio_url', 'applied_at', 'job',
    ]
    list_editable = ['status']
    date_hierarchy = 'applied_at'
    actions = ['mark_shortlisted', 'mark_rejected']
    fieldsets = (
        ('Candidat', {
            'fields': ('first_name', 'last_name', 'email', 'phone', 'linkedin_url', 'portfolio_url')
        }),
        ('Documents', {
            'fields': ('job', 'cv_file', 'cover_letter')
        }),
        ('Traitement RH', {
            'fields': ('status', 'admin_notes', 'applied_at')
        }),
    )

    @admin.display(description='Candidat')
    def full_name_col(self, obj):
        return obj.full_name

    @admin.action(description='Marquer comme présélectionné(e)')
    def mark_shortlisted(self, request, queryset):
        queryset.update(status=JobApplication.Status.SHORTLIST)

    @admin.action(description='Marquer comme rejeté(e)')
    def mark_rejected(self, request, queryset):
        queryset.update(status=JobApplication.Status.REJECTED)
