from django.contrib import admin
from django.utils.html import format_html
from .models import CameraClip, FaceProfile, RecognitionLog, UserProfile, ObjectDetectionLog


@admin.register(FaceProfile)
class FaceProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'name', 'is_active', 'created_at', 'image_preview']
    list_filter = ['is_active', 'created_at', 'user']
    search_fields = ['name', 'user__username']
    readonly_fields = ['created_at', 'updated_at', 'image_preview']

    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="max-height: 100px; max-width: 100px; border-radius: 50%;" />', obj.image.url)
        return "No Image"
    image_preview.short_description = "Face Image"


@admin.register(RecognitionLog)
class RecognitionLogAdmin(admin.ModelAdmin):
    list_display = ['user', 'recognized_name', 'confidence', 'is_successful', 'created_at', 'image_preview']
    list_filter = ['is_successful', 'created_at', 'user']
    search_fields = ['recognized_name', 'user__username']
    readonly_fields = ['created_at', 'image_preview']

    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="max-height: 100px; max-width: 100px;" />', obj.image.url)
        return "No Image"
    image_preview.short_description = "Image Preview"


@admin.register(ObjectDetectionLog)
class ObjectDetectionLogAdmin(admin.ModelAdmin):
    list_display = ['user', 'object_name', 'confidence', 'location', 'created_at', 'image_preview']
    list_filter = ['object_name', 'created_at', 'user', 'location']
    search_fields = ['object_name', 'user__username', 'location']
    readonly_fields = ['created_at', 'image_preview', 'bounding_box_display']
    
    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="max-height: 150px; max-width: 150px; border: 1px solid #ddd; border-radius: 4px;" />',
                obj.image.url
            )
        return "No Image"
    image_preview.short_description = "Detected Object Image"
    
    def bounding_box_display(self, obj):
        bbox = obj.get_bounding_box()
        if bbox:
            return format_html(
                '<div style="font-family: monospace; background: #f8f9fa; padding: 8px; border-radius: 4px;">'
                'X: {}<br/>Y: {}<br/>Width: {}<br/>Height: {}</div>',
                bbox.get('x', 'N/A'),
                bbox.get('y', 'N/A'), 
                bbox.get('width', 'N/A'),
                bbox.get('height', 'N/A')
            )
        return "No bounding box data"
    bounding_box_display.short_description = "Bounding Box"

    # Custom fieldsets for better organization in detail view
    fieldsets = (
        ('Detection Info', {
            'fields': ('user', 'object_name', 'confidence', 'location')
        }),
        ('Image & Data', {
            'fields': ('image', 'image_preview', 'bounding_box', 'bounding_box_display', 'additional_data')
        }),
        ('Timestamps', {
            'fields': ('created_at',)
        }),
    )


@admin.register(CameraClip)
class CameraClipAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'clip_type',
        'detection_summary',
        'device_id_text',
        'created_at',
        'file_link',
        'image_preview',
    ]
    list_filter = ['clip_type', 'created_at']
    search_fields = ['user__username', 'device_id_text']
    readonly_fields = ['created_at', 'file_link', 'image_preview', 'detection_details']

    def file_link(self, obj):
        if not obj.file:
            return 'No file'
        return format_html(
            '<a href="{}" target="_blank" rel="noopener">Open file</a>',
            obj.file.url,
        )

    file_link.short_description = 'File'

    def image_preview(self, obj):
        if not obj.file:
            return 'No file'
        name = obj.file.name.lower()
        if name.endswith(('.jpg', '.jpeg', '.png', '.webp', '.gif')):
            return format_html(
                '<img src="{}" style="max-height: 120px; max-width: 160px; border-radius: 4px;" />',
                obj.file.url,
            )
        return format_html(
            '<a href="{}" target="_blank" rel="noopener">Download</a>',
            obj.file.url,
        )

    image_preview.short_description = 'Preview'


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'auto_sync', 'face_recognition_tolerance', 'created_at']
    list_filter = ['auto_sync', 'created_at']
    search_fields = ['user__username']
    readonly_fields = ['created_at', 'updated_at']
