from django.contrib import admin
from .models import Document, DocumentSegment, Organization, Risk, Control, DocumentTemplate, DocumentRiskControl
from django.urls import reverse
from django.utils.html import format_html


class DocumentSegmentInline(admin.StackedInline):
    model = DocumentSegment
    extra = 1
    ordering = ['order']
    fields = ('segment_type', 'content', 'order')
    
class DocumentAdmin(admin.ModelAdmin):
    inlines = [DocumentSegmentInline]
    list_display = ('organization', 'created_at', 'modified_at')
    search_fields = ['organization__name']
    readonly_fields = ('created_at', 'modified_at')

class DocumentTemplateAdmin(admin.ModelAdmin):
    list_display = ['name', 'created_at', 'updated_at', 'preview_button']

    def preview_button(self, obj):
        url = reverse('core:template_preview', args=[obj.name])
        return format_html('<a href="{}" target="_blank">Preview</a>', url)

    preview_button.short_description = 'Preview'
    preview_button.allow_tags = True


class OrganizationAdmin(admin.ModelAdmin):
    list_display = ('name', 'email', 'industry_sector')
    search_fields = ['name', 'email']

class RiskAdmin(admin.ModelAdmin):
    ordering = ['risk_id']
    list_display = ['risk_id','risk_name','category']

class ControlAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')

class DocumentRiskControlAdmin(admin.ModelAdmin):
    list_display = ('document', 'risk', 'control', 'weight')


admin.site.register(Document, DocumentAdmin)
admin.site.register(Organization, OrganizationAdmin)
admin.site.register(Risk ,RiskAdmin)
admin.site.register(Control, ControlAdmin)
admin.site.register(DocumentTemplate, DocumentTemplateAdmin)
admin.site.register(DocumentRiskControl, DocumentRiskControlAdmin)
