import json
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.utils.html import format_html

from .models import Appointment, WebhookEvent, FeatureFlag, OutboundMessage


@admin.register(Appointment)
class AppointmentAdmin(admin.ModelAdmin):
    list_display = ['name', 'id', 'company', 'scheduled_date', 'booking_type', 'offtime', 'appointment_phone']
    list_filter = ['company', 'offtime', 'scheduled_date']
    search_fields = ['user__username', 'company__name']
    ordering = ['-scheduled_date']


@admin.register(WebhookEvent)
class WebhookEventAdmin(admin.ModelAdmin):
    list_display = ['source', 'event_type', 'success', 'received_at']
    readonly_fields = (
        "source",
        "event_type",
        "success",
        "headers",
        "raw_payload",
        "processed",
        "processed_at",
        "received_at",
        "error_message"
    )
    list_filter = ['event_type', 'received_at']
    search_fields = ['id', 'event_type']
    ordering = ['-received_at']


@admin.register(FeatureFlag)
class FeatureFlagAdmin(admin.ModelAdmin):
    list_display = ("key", "enabled")
    list_editable = ("enabled",)


@admin.register(OutboundMessage)
class OutboundMessageAdmin(admin.ModelAdmin):
    """
    Enterprise-grade read-only audit admin for outbound communications.
    Fully immutable and non-deletable.
    """

    # -------- LIST VIEW --------
    list_display = (
        "id",
        "channel",
        "to",
        "status_badge",
        "provider_message_id",
        "created_at",
        "sent_at",
        "delivered_at",
    )

    list_filter = (
        "channel",
        "status",
        "created_at",
        "sent_at",
        "delivered_at",
    )

    search_fields = (
        "id",
        "to",
        "subject",
        "provider_message_id",
        "twilio_call_sid",
        "retell_call_id",
        "error_message",
    )

    ordering = ("-created_at",)
    date_hierarchy = "created_at"

    # -------- READ-ONLY FIELDS --------
    readonly_fields = (
        "id",
        "channel",
        "to",
        "subject",
        "template_name",
        "context_pretty",
        "message_payload_pretty",
        "provider_message_id",
        "twilio_call_sid",
        "retell_call_id",
        "status",
        "error_message",
        "created_at",
        "sent_at",
        "delivered_at",
    )

    # -------- FIELD GROUPING --------
    fieldsets = (
        ("Basic Info", {
            "fields": (
                "id",
                "channel",
                "status",
                "to",
                "subject",
            )
        }),
        ("Template & Payload", {
            "classes": ("collapse",),
            "fields": (
                "template_name",
                "context_pretty",
                "message_payload_pretty",
            )
        }),
        ("Provider Details", {
            "classes": ("collapse",),
            "fields": (
                "provider_message_id",
                "twilio_call_sid",
                "retell_call_id",
            )
        }),
        ("Timestamps", {
            "fields": (
                "created_at",
                "sent_at",
                "delivered_at",
            )
        }),
        ("Errors", {
            "classes": ("collapse",),
            "fields": ("error_message",),
        }),
    )

    # -------- PRETTY JSON RENDERING --------
    def context_pretty(self, obj):
        return self._pretty_json(obj.context)

    context_pretty.short_description = "Context (JSON)"

    def message_payload_pretty(self, obj):
        return self._pretty_json(obj.message_payload)

    message_payload_pretty.short_description = "Message Payload (JSON)"

    def _pretty_json(self, data):
        if not data:
            return "-"
        formatted = json.dumps(data, indent=2, sort_keys=True)
        return mark_safe(
            f"<pre style='max-height:400px;overflow:auto;background:#111;color:#0f0;padding:10px;'>{formatted}</pre>"
        )

    # -------- STATUS COLOR BADGE --------
    def status_badge(self, obj):
        colors = {
            "pending": "#f59e0b",
            "sent": "#3b82f6",
            "delivered": "#10b981",
            "failed": "#ef4444",
        }
        color = colors.get(obj.status, "#6b7280")
        status_text = obj.status.upper()
        return format_html(
            '<span style="color:white;background:{color};padding:4px 8px;border-radius:6px;">{status}</span>',
            color=color,
            status=status_text
        )

    status_badge.short_description = "Status"

    # -------- HARD IMMUTABILITY --------
    def has_add_permission(self, request):
        return False  # Cannot manually create audit logs

    def has_delete_permission(self, request, obj=None):
        return False  # Cannot delete from admin

    def has_change_permission(self, request, obj=None):
        # Allow viewing but no editing
        if request.method in ["GET", "HEAD"]:
            return True
        return False

    # Extra protection against bulk delete
    def get_actions(self, request):
        actions = super().get_actions(request)
        if "delete_selected" in actions:
            del actions["delete_selected"]
        return actions
