from django.contrib import admin
from django.utils.html import format_html
from .models import TelegramBot, BotConfig, TelegramChat


@admin.register(TelegramBot)
class TelegramBotAdmin(admin.ModelAdmin):
    list_display = ("name", "username", "is_active", "_has_config")
    list_editable = ("is_active",)
    search_fields = ("name", "username")

    @admin.display(
        description="Имеет конфиг",
        boolean=True,
    )
    def _has_config(self, obj):
        return bool(getattr(obj, "config", None))


@admin.register(BotConfig)
class BotConfigAdmin(admin.ModelAdmin):
    list_display = ("bot", "parse_mode", "use_webhook", "_allowed_len", "_admins_len", "_webhook")
    list_editable = ("use_webhook",)
    fieldsets = (
        (None, {"fields": ("bot", "parse_mode")}),
        ("Обновления и доступ", {"fields": ("allowed_updates", "admin_user_ids")}),
        ("Webhook", {"fields": ("use_webhook", "webhook_url")}),
    )

    @admin.display(description="allowed_updates")
    def _allowed_len(self, obj):
        return len(obj.allowed_updates or [])

    @admin.display(description="admins")
    def _admins_len(self, obj):
        return len(obj.admin_user_ids or [])

    @admin.display(description="webhook_url")
    def _webhook(self, obj):
        if obj.use_webhook and obj.webhook_url:
            return format_html("<a href='{0}' target='_blank'>{0}</a>", obj.webhook_url)
        return "—"


@admin.register(TelegramChat)
class TelegramChatAdmin(admin.ModelAdmin):
    list_display = ("bot", "chat_id", "type", "title", "username", "is_member", "joined_at", "left_at", "last_message_at")
    list_filter = ("bot", "type", "is_member")
    search_fields = ("chat_id", "title", "username")
    ordering = ("-is_member", "-joined_at")