"""Django admin configuration for platform_core models."""

from __future__ import annotations

from django.contrib import admin
from django.utils.translation import gettext_lazy as _

from simorgh.apps.platform_core.models import (
    Activity,
    Attachment,
    Comment,
    CustomFieldDefinition,
    CustomFieldValue,
    DocumentTemplate,
    ExportJob,
    ExportLayout,
    FormDefinition,
    FormSubmission,
    ImportJob,
    MessageTemplate,
    Note,
    PrintTemplate,
    ReferenceNumberSequence,
    Tag,
    TagAssignment,
)


@admin.register(ReferenceNumberSequence)
class ReferenceNumberSequenceAdmin(admin.ModelAdmin):
    """Admin for managing per-tenant reference-number sequences."""

    list_display = (
        "entity_type",
        "prefix",
        "format",
        "last_number",
        "reset_yearly",
        "use_jalali_year",
        "is_active",
        "tenant",
    )
    list_filter = ("is_active", "reset_yearly", "use_jalali_year", "tenant")
    search_fields = ("entity_type", "prefix", "tenant__name")
    readonly_fields = ("last_number", "last_reset_year", "public_id", "created_at", "updated_at")
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "tenant",
                    "organization_node",
                    "entity_type",
                    "prefix",
                    "format",
                    "is_active",
                ),
            },
        ),
        (
            _("Counter state"),
            {
                "fields": ("last_number", "last_reset_year"),
                "description": _(
                    "These fields are managed automatically. "
                    "Edit only to correct data inconsistencies."
                ),
            },
        ),
        (
            _("Options"),
            {
                "fields": ("reset_yearly", "use_jalali_year"),
            },
        ),
        (
            _("Metadata"),
            {
                "fields": ("public_id", "created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )
    ordering = ("tenant", "entity_type")


class FormSubmissionInline(admin.TabularInline):
    """Inline view of submissions inside a FormDefinition admin page."""

    model = FormSubmission
    extra = 0
    readonly_fields = ("public_id", "submitted_by", "ip_address", "processed", "created_at")
    fields = ("public_id", "submitted_by", "ip_address", "processed", "created_at")
    can_delete = False
    show_change_link = True
    ordering = ("-created_at",)
    max_num = 20


@admin.register(FormDefinition)
class FormDefinitionAdmin(admin.ModelAdmin):
    """Admin for managing dynamic form definitions."""

    list_display = (
        "title",
        "entity_type",
        "submit_action",
        "is_active",
        "public_url_slug",
        "tenant",
        "created_at",
    )
    list_filter = ("is_active", "submit_action", "tenant")
    search_fields = ("title", "public_url_slug", "tenant__name")
    readonly_fields = ("public_id", "created_by", "created_at", "updated_at")
    inlines = [FormSubmissionInline]
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "tenant",
                    "organization_node",
                    "title",
                    "description",
                    "entity_type",
                    "is_active",
                    "public_url_slug",
                ),
            },
        ),
        (
            _("Form fields"),
            {
                "fields": ("fields",),
                "description": _(
                    "JSON array of field descriptors: "
                    "[{id, type, label, required, options, validation}]."
                ),
            },
        ),
        (
            _("Submit action"),
            {
                "fields": ("submit_action", "submit_config"),
            },
        ),
        (
            _("Metadata"),
            {
                "fields": ("public_id", "created_by", "created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )
    ordering = ("-created_at",)


@admin.register(FormSubmission)
class FormSubmissionAdmin(admin.ModelAdmin):
    """Admin for reviewing form submissions."""

    list_display = ("public_id", "form", "submitted_by", "ip_address", "processed", "created_at")
    list_filter = ("processed", "form__tenant", "form")
    search_fields = ("form__title", "submitted_by__username", "ip_address")
    readonly_fields = (
        "public_id",
        "form",
        "submitted_by",
        "ip_address",
        "data",
        "processed",
        "created_at",
        "updated_at",
    )
    ordering = ("-created_at",)

    def has_add_permission(self, request) -> bool:  # noqa: ARG002
        return False


@admin.register(ImportJob)
class ImportJobAdmin(admin.ModelAdmin):
    """Read-only admin for bulk import jobs."""

    list_display = (
        "public_id",
        "entity_type",
        "status",
        "total_rows",
        "processed_rows",
        "error_rows",
        "created_by",
        "created_at",
    )
    list_filter = ("status", "entity_type", "tenant")
    search_fields = ("entity_type", "created_by__username", "public_id")
    readonly_fields = (
        "public_id",
        "tenant",
        "organization_node",
        "entity_type",
        "file",
        "status",
        "total_rows",
        "processed_rows",
        "error_rows",
        "error_report",
        "started_at",
        "finished_at",
        "created_by",
        "created_at",
        "updated_at",
    )
    ordering = ("-created_at",)

    def has_add_permission(self, request) -> bool:  # noqa: ARG002
        return False

    def has_change_permission(self, request, obj=None) -> bool:  # noqa: ARG002
        return False


@admin.register(ExportJob)
class ExportJobAdmin(admin.ModelAdmin):
    list_display = (
        "entity_type",
        "format",
        "status",
        "row_count",
        "created_by",
        "created_at",
    )
    list_filter = ("status", "format", "entity_type", "tenant")
    search_fields = ("entity_type", "created_by__username")
    readonly_fields = (
        "public_id",
        "tenant",
        "organization_node",
        "entity_type",
        "format",
        "filters",
        "status",
        "file",
        "row_count",
        "error_message",
        "started_at",
        "finished_at",
        "created_by",
        "created_at",
        "updated_at",
    )
    ordering = ("-created_at",)

    def has_add_permission(self, request) -> bool:  # noqa: ARG002
        return False

    def has_change_permission(self, request, obj=None) -> bool:  # noqa: ARG002
        return False


@admin.register(PrintTemplate)
class PrintTemplateAdmin(admin.ModelAdmin):
    list_display = (
        "name",
        "entity_type",
        "paper_size",
        "orientation",
        "is_active",
        "tenant",
        "created_at",
    )
    list_filter = ("is_active", "paper_size", "orientation", "entity_type", "tenant")
    search_fields = ("name", "entity_type")
    readonly_fields = (
        "public_id",
        "tenant",
        "organization_node",
        "created_by",
        "created_at",
        "updated_at",
    )
    fieldsets = (
        (None, {"fields": ("tenant", "organization_node", "entity_type", "name", "is_active")}),
        (_("Template"), {"fields": ("html_template", "css")}),
        (_("Page setup"), {"fields": ("paper_size", "orientation")}),
        (_("Meta"), {"fields": ("public_id", "created_by", "created_at", "updated_at"), "classes": ("collapse",)}),
    )
    ordering = ("entity_type", "name")


@admin.register(MessageTemplate)
class MessageTemplateAdmin(admin.ModelAdmin):
    """Admin for managing tenant message templates."""

    list_display = (
        "code",
        "name",
        "channel",
        "language",
        "is_active",
        "tenant",
        "created_at",
    )
    list_filter = ("is_active", "channel", "language", "tenant")
    search_fields = ("code", "name", "tenant__name")
    readonly_fields = (
        "public_id",
        "tenant",
        "organization_node",
        "created_by",
        "created_at",
        "updated_at",
    )
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "tenant",
                    "organization_node",
                    "code",
                    "name",
                    "channel",
                    "language",
                    "is_active",
                ),
            },
        ),
        (
            _("Content"),
            {
                "fields": ("subject", "body"),
            },
        ),
        (
            _("Variables"),
            {
                "fields": ("variables",),
                "description": _(
                    "JSON list of variable descriptors: [{name, type, description}]."
                ),
            },
        ),
        (
            _("Metadata"),
            {
                "fields": ("public_id", "created_by", "created_at", "updated_at"),
                "classes": ("collapse",),
            },
        ),
    )
    ordering = ("code", "language")


# ---------------------------------------------------------------------------
# Shared content models — lightweight admin views
# ---------------------------------------------------------------------------

@admin.register(Attachment)
class AttachmentAdmin(admin.ModelAdmin):
    list_display = ("file", "kind", "content_type", "tenant", "uploaded_by", "created_at")
    list_filter = ("kind", "tenant")
    search_fields = ("file__filename", "tenant__name", "description")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("-created_at",)


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ("author", "content_type", "object_id", "tenant", "created_at")
    list_filter = ("content_type", "tenant")
    search_fields = ("body", "author__username", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("-created_at",)


@admin.register(Activity)
class ActivityAdmin(admin.ModelAdmin):
    list_display = ("actor", "verb", "content_type", "object_id", "tenant", "occurred_at")
    list_filter = ("verb", "content_type", "tenant")
    search_fields = ("actor__username", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("-occurred_at",)


@admin.register(CustomFieldDefinition)
class CustomFieldDefinitionAdmin(admin.ModelAdmin):
    list_display = ("key", "entity_type", "field_type", "is_required", "tenant", "created_at")
    list_filter = ("entity_type", "field_type", "is_required", "tenant")
    search_fields = ("key", "label_key", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("entity_type", "key")


@admin.register(CustomFieldValue)
class CustomFieldValueAdmin(admin.ModelAdmin):
    list_display = ("definition", "object_id", "tenant", "created_at")
    list_filter = ("definition__entity_type", "tenant")
    search_fields = ("definition__key", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("-created_at",)


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ("name", "color", "tenant", "created_at")
    list_filter = ("tenant",)
    search_fields = ("name", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("name",)


@admin.register(TagAssignment)
class TagAssignmentAdmin(admin.ModelAdmin):
    list_display = ("tag", "content_type", "object_id", "tenant", "created_at")
    list_filter = ("content_type", "tenant")
    search_fields = ("tag__name", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("-created_at",)


@admin.register(Note)
class NoteAdmin(admin.ModelAdmin):
    list_display = ("content_type", "object_id", "author", "visibility", "tenant", "created_at")
    list_filter = ("visibility", "tenant")
    search_fields = ("body", "author__username", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("-created_at",)


@admin.register(DocumentTemplate)
class DocumentTemplateAdmin(admin.ModelAdmin):
    list_display = ("name", "entity_type", "is_active", "tenant", "created_at")
    list_filter = ("entity_type", "is_active", "tenant")
    search_fields = ("name", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("entity_type", "name")


@admin.register(ExportLayout)
class ExportLayoutAdmin(admin.ModelAdmin):
    list_display = ("name", "entity_type", "is_active", "tenant", "created_at")
    list_filter = ("entity_type", "is_active", "tenant")
    search_fields = ("name", "tenant__name")
    readonly_fields = ("public_id", "created_at", "updated_at")
    ordering = ("entity_type", "name")

