import logging

from django.conf import settings as s
from django.contrib import admin
from django.contrib import messages

from .models import (
    AdditionalInformation,
    ClassifierPluginModel,
    Compound,
    CompoundStructure,
    Edge,
    EnviFormer,
    ExternalDatabase,
    ExternalIdentifier,
    Group,
    GroupPackagePermission,
    JobLog,
    License,
    MLRelativeReasoning,
    Node,
    ParallelRule,
    Pathway,
    PropertyPluginModel,
    Reaction,
    Scenario,
    Setting,
    SimpleAmbitRule,
    User,
    UserPackagePermission,
)

Package = s.GET_PACKAGE_MODEL()

logger = logging.getLogger(__name__)


class AdditionalInformationAdmin(admin.ModelAdmin):
    pass


class UserAdmin(admin.ModelAdmin):
    list_display = [
        "username",
        "email",
        "is_active",
        "is_staff",
        "is_superuser",
        "last_login",
        "date_joined",
    ]

    actions = ["send_welcome_mail", "send_affiliation_mail"]

    @admin.action(description="Send welcome mail")
    def send_welcome_mail(self, request, queryset):
        from django.core.mail import EmailMultiAlternatives

        tpl = """Hello {username},

Your account has been successfully activated.

To log in, please visit
https://envipath.org/password_reset/
and request a new password.

If you have any questions or feedback, feel free to visit our community forum at
https://community.envipath.org/.
You do not need to register again for the forum - you can log in using your enviPath account by clicking "Log In" and then "Log in with enviPath."

Best regards,

The enviPath Team"""

        users = []

        for user in queryset:
            if user.is_active:
                logger.info(f"{user.username} already active - not sending mail again")
                continue
            try:
                msg = EmailMultiAlternatives(
                    "Your enviPath Account Is Now Active",
                    tpl.format(username=user.username),
                    "admin@envipath.org",
                    [user.email],
                    bcc=["admin@envipath.org"],
                )

                msg.send(fail_silently=False)

                user.is_active = True
                user.password = "ASDF"
                user.save()

                users.append(user)
                logger.info(f"{user.username} -> {user.email} mail sent")
            except Exception as e:
                logger.info(f"Error sending mail to {user.username}: {e}")

        self.message_user(
            request, f"Sent welcome mail to {[u.email for u in users]}", messages.SUCCESS
        )

    @admin.action(description="Send affiliation mail")
    def send_affiliation_mail(self, request, queryset):
        from django.core.mail import EmailMultiAlternatives

        tpl = """Dear {username},

Thank you for your interest in enviPath!

Please note that the public enviPath system is intended for non-commercial use only.
We see that you registered using the email address {email}.
If possible, we kindly ask you to register using an official email address that reflects your affiliation (e.g., a university, NGO, or research organization).

If you would like us to update your account, simply reply to this email and let us know which address we should use.
We will then change it in our system, and you will receive a password reset email at the new address.

If you are registering with a company email address and are interested in commercial use, you are very welcome to book a meeting with us so we can discuss how we can best support you.
To book a meeting, please visit https://envipath.com/book

If changing to an affiliation email address is not possible, please contact us at registration@envipath.org

Best regards,

enviPath team"""

        users = []

        for user in queryset:
            if user.is_active or user.contacted:
                logger.info(
                    f"{user.username} already active or already contacted - not sending mail again"
                )
                continue
            try:
                msg = EmailMultiAlternatives(
                    "Regarding your enviPath registration",
                    tpl.format(username=user.username, email=user.email),
                    "admin@envipath.org",
                    [user.email],
                    bcc=["admin@envipath.org"],
                )

                msg.send(fail_silently=False)

                user.contacted = True
                user.save()

                users.append(user)
                logger.info(f"{user.username} -> {user.email} affiliation mail sent")
            except Exception as e:
                logger.info(f"Error sending mail to {user.username}: {e}")

        self.message_user(
            request, f"Sent affiliation mail to {[u.email for u in users]}", messages.SUCCESS
        )


class UserPackagePermissionAdmin(admin.ModelAdmin):
    pass


class GroupAdmin(admin.ModelAdmin):
    pass


class GroupPackagePermissionAdmin(admin.ModelAdmin):
    pass


class JobLogAdmin(admin.ModelAdmin):
    pass


class EPAdmin(admin.ModelAdmin):
    search_fields = ["name", "description", "url", "uuid"]
    list_display = ["name", "url", "created"]
    ordering = ["-created"]


class PackageAdmin(EPAdmin):
    pass


class MLRelativeReasoningAdmin(EPAdmin):
    pass


class EnviFormerAdmin(EPAdmin):
    pass


class PropertyPluginModelAdmin(admin.ModelAdmin):
    pass


class ClassifierPluginModelAdmin(admin.ModelAdmin):
    pass


class LicenseAdmin(admin.ModelAdmin):
    list_display = ["cc_string", "link", "image_link"]


class CompoundAdmin(EPAdmin):
    pass


class CompoundStructureAdmin(EPAdmin):
    pass


class SimpleAmbitRuleAdmin(EPAdmin):
    pass


class ParallelRuleAdmin(EPAdmin):
    pass


class ReactionAdmin(EPAdmin):
    pass


class PathwayAdmin(EPAdmin):
    pass


class NodeAdmin(EPAdmin):
    pass


class EdgeAdmin(EPAdmin):
    pass


class ScenarioAdmin(EPAdmin):
    pass


class SettingAdmin(EPAdmin):
    pass


class ExternalDatabaseAdmin(admin.ModelAdmin):
    pass


class ExternalIdentifierAdmin(admin.ModelAdmin):
    pass


admin.site.register(AdditionalInformation, AdditionalInformationAdmin)
admin.site.register(User, UserAdmin)
admin.site.register(UserPackagePermission, UserPackagePermissionAdmin)
admin.site.register(Group, GroupAdmin)
admin.site.register(GroupPackagePermission, GroupPackagePermissionAdmin)
admin.site.register(JobLog, JobLogAdmin)
admin.site.register(Package, PackageAdmin)
admin.site.register(MLRelativeReasoning, MLRelativeReasoningAdmin)
admin.site.register(EnviFormer, EnviFormerAdmin)
admin.site.register(PropertyPluginModel, PropertyPluginModelAdmin)
admin.site.register(License, LicenseAdmin)
admin.site.register(ClassifierPluginModel, ClassifierPluginModelAdmin)
admin.site.register(Compound, CompoundAdmin)
admin.site.register(CompoundStructure, CompoundStructureAdmin)
admin.site.register(SimpleAmbitRule, SimpleAmbitRuleAdmin)
admin.site.register(ParallelRule, ParallelRuleAdmin)
admin.site.register(Reaction, ReactionAdmin)
admin.site.register(Pathway, PathwayAdmin)
admin.site.register(Node, NodeAdmin)
admin.site.register(Edge, EdgeAdmin)
admin.site.register(Setting, SettingAdmin)
admin.site.register(Scenario, ScenarioAdmin)
admin.site.register(ExternalDatabase, ExternalDatabaseAdmin)
admin.site.register(ExternalIdentifier, ExternalIdentifierAdmin)
