from django.contrib import admin
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from .models import Announcement, AnnouncementView


@admin.register(Announcement)
class AnnouncementAdmin(admin.ModelAdmin):
    list_display  = [
        "title_display", "category_badge", "neighborhood_display",
        "priority_badge", "is_active", "broadcast_status",
        "views_count", "created_at",
    ]
    list_filter   = ["category", "neighborhood", "priority", "is_active", "is_broadcast"]
    search_fields = ["title", "body"]
    readonly_fields = [
        "created_by", "created_at", "updated_at",
        "broadcast_done", "views_count_display",
    ]
    list_editable  = ["is_active"]
    date_hierarchy = "created_at"

    fieldsets = (
        ("Content", {
            "fields": ("title", "body", "image", "link"),
        }),
        ("Targeting", {
            "fields": ("category", "neighborhood", "priority", "expires_at"),
            "description": "Choose who sees this and how urgently.",
        }),
        ("Broadcast to Chat Rooms", {
            "fields": ("is_broadcast",),
            "description": (
                "Enable to automatically send this announcement as a message "
                "into relevant neighbourhood chat rooms. Sent once on save."
            ),
        }),
        ("Status", {
            "fields": (
                "is_active", "broadcast_done",
                "created_by", "created_at", "updated_at", "views_count_display",
            ),
            "classes": ("collapse",),
        }),
    )

    def title_display(self, obj):
        return format_html("<strong>{}</strong>", obj.title)
    title_display.short_description = "Title"

    def category_badge(self, obj):
        colors = {
            "taarifa":  ("#ef4444", "#fef2f2"),
            "shughuli": ("#8b5cf6", "#f5f3ff"),
            "biashara": ("#f59e0b", "#fffbeb"),
            "kazi":     ("#10b981", "#f0fdf4"),
            "matatu":   ("#3b82f6", "#eff6ff"),
            "harambee": ("#ec4899", "#fdf2f8"),
            "general":  ("#6b7280", "#f9fafb"),
        }
        color, bg = colors.get(obj.category, ("#6b7280", "#f9fafb"))
        label = obj.get_category_display().split("—")[0].strip()
        return mark_safe(
            f'<span style="background:{bg};color:{color};padding:3px 10px;'
            f'border-radius:12px;font-size:0.78em;font-weight:700;">{label}</span>'
        )
    category_badge.short_description = "Category"

    def neighborhood_display(self, obj):
        label = obj.get_neighborhood_display()
        if obj.neighborhood == "all":
            return mark_safe(
                f'<span style="color:#667eea;font-weight:700;">{label} (All)</span>'
            )
        return mark_safe(
            f'<span style="color:#374151;font-weight:600;">{label}</span>'
        )
    neighborhood_display.short_description = "Area"

    def priority_badge(self, obj):
        styles = {
            "normal": ("#10b981", "Normal"),
            "high":   ("#d97706", "High"),
            "urgent": ("#ef4444", "URGENT"),
        }
        color, label = styles.get(obj.priority, ("#6b7280", "Normal"))
        return mark_safe(
            f'<span style="color:{color};font-weight:800;font-size:0.82em;">{label}</span>'
        )
    priority_badge.short_description = "Priority"

    def broadcast_status(self, obj):
        if not obj.is_broadcast:
            return mark_safe('<span style="color:#9ca3af;">—</span>')
        if obj.broadcast_done:
            return mark_safe('<span style="color:#10b981;font-weight:700;">Sent</span>')
        return mark_safe('<span style="color:#f59e0b;font-weight:700;">Pending</span>')
    broadcast_status.short_description = "Broadcast"

    def views_count(self, obj):
        count = obj.views.count()
        return mark_safe(
            f'<span style="color:#667eea;font-weight:700;">{count}</span>'
        )
    views_count.short_description = "Views"

    def views_count_display(self, obj):
        return obj.views.count()
    views_count_display.short_description = "Total views"

    def save_model(self, request, obj, form, change):
        if not obj.pk:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)
        if obj.is_broadcast and not obj.broadcast_done:
            self._broadcast_to_rooms(obj)

    def _broadcast_to_rooms(self, announcement):
        try:
            from community.models import Room, Message as RoomMessage

            admin_user = announcement.created_by

            if announcement.neighborhood == "all":
                rooms = Room.objects.filter(is_active=True)
            else:
                rooms = Room.objects.filter(
                    neighborhood=announcement.neighborhood,
                    is_active=True
                )

            cat = announcement.get_category_display().split("—")[0].strip().upper()
            msg_text = (
                f"[{cat}]\n\n"
                f"{announcement.title}\n\n"
                f"{announcement.body}"
            )
            if announcement.link:
                msg_text += f"\n\nLink: {announcement.link}"

            for room in rooms:
                RoomMessage.objects.create(
                    room=room,
                    user=admin_user,
                    content=msg_text,
                    is_announcement=True,
                )

            announcement.broadcast_done = True
            announcement.save(update_fields=["broadcast_done"])

        except Exception as e:
            print(f"Broadcast failed: {e}")


@admin.register(AnnouncementView)
class AnnouncementViewAdmin(admin.ModelAdmin):
    list_display    = ["announcement", "user", "viewed_at"]
    list_filter     = ["announcement__category"]
    search_fields   = ["user__username", "announcement__title"]
    readonly_fields = ["announcement", "user", "viewed_at"]