from django_admin_listfilter_dropdown.filters import RelatedOnlyDropdownFilter
from django_object_actions import DjangoObjectActions, takes_instance_or_queryset
from import_export.admin import ExportMixin
from simple_history.admin import SimpleHistoryAdmin

from django.contrib import admin, messages
from django.utils.translation import gettext_lazy as _

from lms.mailing.models import CourseFollower, CourseFollowerHistory, CourseMailing, Mailing, MailingEvent

from .forms import MailingForm
from .resources import CourseFollowerHistoryResource, CourseFollowerResource
from .services import check_mailing_events, process_mailing_event


@admin.register(Mailing)
class MailingAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'intended_for', 'is_active', 'created', 'modified')
    list_filter = ('is_active',)
    form = MailingForm
    fields = ('mailing_task', 'name', 'intended_for', 'is_active')


@admin.register(CourseMailing)
class CourseMailingAdmin(admin.ModelAdmin):
    list_display = ('course', 'mailing', 'is_active', 'created', 'modified')
    list_select_related = ('course', 'mailing')
    list_filter = ('is_active',)
    raw_id_fields = ('course',)
    fields = ('course', 'mailing', 'can_group_with_others', 'is_active')


@admin.register(CourseFollower)
class CourseFollowerAdmin(ExportMixin, SimpleHistoryAdmin):
    list_display = (
        'user', 'course', 'is_active', 'subscribed_date', 'unsubscribed_date', 'unsubscription_reason',
    )
    list_select_related = ('user', 'user__staffprofile', 'course')
    list_filter = (
        ('course', RelatedOnlyDropdownFilter),
        'is_active',
        'unsubscription_reason',
    )
    raw_id_fields = ('user', 'course')
    readonly_fields = ('created', 'modified')
    fields = (
        'user', 'course', 'is_active',
        'subscribed_date', 'unsubscribed_date', 'unsubscription_reason',
    ) + readonly_fields
    resource_class = CourseFollowerResource


@admin.register(CourseFollowerHistory)
class CourseFollowerHistoryAdmin(ExportMixin, admin.ModelAdmin):
    list_display = (
        'user', 'course', 'is_active', 'unsubscription_reason', 'created', 'modified',
        'history_type', 'history_change_reason', 'history_date', 'history_user',
    )
    list_select_related = ('user', 'course', 'history_user')
    list_filter = (
        ('course', RelatedOnlyDropdownFilter),
        'is_active',
        'unsubscription_reason',
    )
    raw_id_fields = ('user', 'course', 'history_user')
    resource_class = CourseFollowerHistoryResource


@admin.register(MailingEvent)
class MailingEventAdmin(DjangoObjectActions, admin.ModelAdmin):
    list_display = ('mailing', 'status', 'course', 'recipient', 'created', 'modified')
    list_select_related = ('mailing',)
    list_filter = ('status',)
    raw_id_fields = ('courses', 'recipients')

    actions = [
        'resend_mailing_event_action',
        'check_mailing_event_action',
    ]

    change_actions = [
        'resend_mailing_event_action',
        'check_mailing_event_action',
    ]

    @takes_instance_or_queryset
    def resend_mailing_event_action(self, request, queryset):
        for mailing_event in queryset:
            process_mailing_event(mailing_event=mailing_event, force=True)
            level = messages.INFO
            message = _(f"Письмо {mailing_event} переотправлено")
            if mailing_event.status == MailingEvent.Status.ERROR:
                level = messages.ERROR
                message = _(f"Ошибка переотправки письма {mailing_event}")

            self.message_user(
                request=request,
                message=message,
                level=level,
            )

    resend_mailing_event_action.short_description = _("переотправить письмо")
    resend_mailing_event_action.label = _("переотправить письмо")

    @takes_instance_or_queryset
    def check_mailing_event_action(self, request, queryset):
        check_mailing_events(
            mailing_event_ids=[mailing_event.id for mailing_event in queryset],
            force=True,
        )
        self.message_user(
            request=request,
            message=_("перезагрузите страницу, чтобы проверить результат"),
            level=messages.INFO,
        )

    check_mailing_event_action.short_description = _("проверить результат отправки")
    check_mailing_event_action.label = _("проверить результат отправки")
