from django.contrib import admin
from django.utils.html import format_html

from .models import GroupPhoto, GroupPhotoAnalysis, Photo, PointOfImpact


@admin.register(Photo)
class PhotoAdmin(admin.ModelAdmin):
    list_display = ('id', 'content_type', 'size_kb', 'width', 'height', 'uploaded_by', 'uploaded_at')
    search_fields = ('uploaded_by__email', 'description', 'content_type')
    readonly_fields = ('size', 'width', 'height', 'uploaded_at', 'preview')
    raw_id_fields = ('uploaded_by',)

    def size_kb(self, obj):
        return f'{obj.size / 1024:.1f} KB'
    size_kb.short_description = 'Size'

    def preview(self, obj):
        return format_html(
            '<img src="/api/photos/{}/data/" style="max-width:300px;max-height:300px;" />',
            obj.pk,
        )
    preview.short_description = 'Preview'

    def get_fields(self, request, obj=None):
        fields = ['content_type', 'size', 'width', 'height', 'uploaded_by', 'description', 'uploaded_at']
        if obj:
            fields.insert(0, 'preview')
        return fields


class GroupPhotoAnalysisInline(admin.StackedInline):
    model = GroupPhotoAnalysis
    extra = 0
    max_num = 1


class PointOfImpactInline(admin.TabularInline):
    model = PointOfImpact
    extra = 0
    fields = ('order', 'shot', 'x_px', 'y_px', 'x_mm', 'y_mm', 'radius_mm', 'notes')
    raw_id_fields = ('shot',)


@admin.register(GroupPhoto)
class GroupPhotoAdmin(admin.ModelAdmin):
    list_display = ('id', 'shot_group', 'caption', 'order')
    search_fields = ('caption', 'shot_group__label', 'shot_group__analysis__name')
    raw_id_fields = ('photo', 'shot_group')
    inlines = [GroupPhotoAnalysisInline, PointOfImpactInline]
