from django.contrib import admin
from django.utils.translation import gettext_lazy as _

from .models import Chat, Message, MessageFile


class MessageFileInline(admin.TabularInline):
    model = MessageFile
    extra = 0
    readonly_fields = ["mime_type", "created_at"]
    fields = ["file", "mime_type", "created_at"]


class MessageInline(admin.TabularInline):
    model = Message
    extra = 0
    readonly_fields = ["content_preview", "created_at"]
    fields = ["role", "content_preview", "created_at"]
    show_change_link = True

    @admin.display(description=_("Content"))
    def content_preview(self, obj: Message) -> str:
        return obj.content[:120]


@admin.register(Chat)
class ChatAdmin(admin.ModelAdmin):
    list_display = ["id", "title", "model", "provider", "created_at", "updated_at"]
    list_filter = ["model", "provider", "created_at"]
    search_fields = ["title"]
    readonly_fields = ["created_at", "updated_at"]
    inlines = [MessageInline]
    fieldsets = [
        (None, {"fields": ["title", "model", "provider"]}),
        (_("System"), {"fields": ["system_prompt"], "classes": ["collapse"]}),
        (_("Meta"), {"fields": ["created_at", "updated_at"]}),
    ]


@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
    list_display = ["id", "chat", "role", "content_preview", "created_at"]
    list_filter = ["role", "created_at"]
    search_fields = ["content", "chat__title"]
    readonly_fields = ["created_at"]
    inlines = [MessageFileInline]
    fields = ["chat", "role", "content", "reasoning", "tool_calls", "tool_results", "created_at"]

    @admin.display(description=_("Content"))
    def content_preview(self, obj: Message) -> str:
        return obj.content[:120]


@admin.register(MessageFile)
class MessageFileAdmin(admin.ModelAdmin):
    list_display = ["id", "message", "file", "mime_type", "created_at"]
    list_filter = ["mime_type", "created_at"]
    search_fields = ["file", "message__content"]
    readonly_fields = ["mime_type", "created_at"]
    fields = ["message", "file", "mime_type", "created_at"]
