from django.contrib import admin
from .models import Rapid, RapidImage, Examination, Site, Abnormality, Region, RapidCreationDefault, Answer, Exam, UserAnswer

from django.forms import ModelForm

from reversion.admin import VersionAdmin
from django.forms.widgets import RadioSelect
from django.contrib import messages

# Register your models here.
admin.site.register(Examination)
#admin.site.register(Site)
admin.site.register(Abnormality)
admin.site.register(Region)
admin.site.register(RapidCreationDefault)
admin.site.register(Answer)

class RapidAnswersInline(admin.TabularInline):
    model = Answer
    extra = 1


class RapidImageInline(admin.TabularInline):
    model = RapidImage
    extra = 1
    readonly_fields = [
        "image_tag",
    ]

class ExamInline(admin.TabularInline):
    model = Rapid.exams.through
    extra = 1


class RapidAdminForm(ModelForm):
    class Meta:
        model = Rapid

        fields = [
            "normal", "abnormality", "region", "laterality", "examination",
            #"site", 
            #"sign", "condition", 
            "feedback", "author"
        ]

        widgets = {
            "laterality": RadioSelect(attrs={'style': 'display: inline-flex'}),
        }


class RapidAdmin(VersionAdmin):
    form = RapidAdminForm

    filter_horizontal = (
        "abnormality",
        "region",
        #"examination",
    )
    save_on_top = True
    save_as = True
    view_on_site = True

    inlines = [
        RapidImageInline,
        RapidAnswersInline,
        ExamInline,
    ]
    actions = ["migrate_to_shorts"]

    def migrate_to_shorts(self, request, queryset):
        """Admin action to migrate selected Rapid questions to shorts.Question"""
        from shorts.models import Question as ShortQuestion

        created = []
        skipped = []
        for rapid in queryset:
            # allow admin or any author to perform migration
            if request.user.is_superuser or rapid.author.filter(id=request.user.id).exists():
                try:
                    q = ShortQuestion.from_rapid(rapid)
                    if q is None:
                        skipped.append(str(rapid.id))
                    else:
                        created.append(str(q.id))
                except Exception as e:
                    self.message_user(request, f"Failed to migrate Rapid {rapid.id}: {e}", level=messages.ERROR)
            else:
                self.message_user(request, f"No permission to migrate Rapid {rapid.id}", level=messages.ERROR)

        if created:
            self.message_user(request, f"Created shorts questions: {', '.join(created)}", level=messages.SUCCESS)
        if skipped:
            self.message_user(request, f"Skipped normal rapids (not migrated): {', '.join(skipped)}", level=messages.INFO)

    migrate_to_shorts.short_description = "Migrate selected rapids to shorts"

class ExamAdmin(VersionAdmin, admin.ModelAdmin):
    save_as = True
    actions = ["migrate_exam_questions"]

    def migrate_exam_questions(self, request, queryset):
        """Admin action to migrate all Rapid questions linked to selected Exam(s)"""
        from shorts.models import Question as ShortQuestion

        created = []
        skipped = []
        for exam in queryset:
            for rapid in exam.exam_questions.all():
                # only allow if admin or author of rapid
                if request.user.is_superuser or rapid.author.filter(id=request.user.id).exists():
                    try:
                        q = ShortQuestion.from_rapid(rapid)
                        if q is None:
                            skipped.append(str(rapid.id))
                        else:
                            created.append(str(q.id))
                    except Exception as e:
                        self.message_user(request, f"Failed to migrate Rapid {rapid.id}: {e}", level=messages.ERROR)
                else:
                    self.message_user(request, f"No permission to migrate Rapid {rapid.id}", level=messages.ERROR)

        if created:
            self.message_user(request, f"Created shorts questions: {', '.join(created)}", level=messages.SUCCESS)
        if skipped:
            self.message_user(request, f"Skipped normal rapids (not migrated): {', '.join(skipped)}", level=messages.INFO)

    migrate_exam_questions.short_description = "Migrate all rapids in selected exam(s) to shorts"

admin.site.register(Rapid, RapidAdmin)
admin.site.register(Exam, ExamAdmin)

class UserAnswerAdmin(admin.ModelAdmin):
    exclude = []
    readonly_fields = ["created", "updated"]

admin.site.register(UserAnswer, UserAnswerAdmin)

class RapidImageAdmin(admin.ModelAdmin):
       readonly_fields = ('rapid',)

admin.site.register(RapidImage, RapidImageAdmin)