from django.contrib import admin
from django.utils.html import format_html
from .models import Call, CallLog, CallPrompt, VapiAssistant, UserAssistantPreference


@admin.register(VapiAssistant)
class VapiAssistantAdmin(admin.ModelAdmin):
    list_display = ['name', 'assistant_id', 'is_active', 'created_at', 'call_count']
    list_filter = ['is_active', 'created_at']
    search_fields = ['name', 'assistant_id']
    readonly_fields = ['created_at', 'call_count']
    actions = ['activate_assistants', 'deactivate_assistants']
    
    fieldsets = (
        ('Assistant Information', {
            'fields': ('name', 'assistant_id', 'is_active')
        }),
        ('Statistics', {
            'fields': ('call_count', 'created_at'),
            'classes': ('collapse',)
        }),
    )
    
    def call_count(self, obj):
        """Display number of calls made with this assistant"""
        if obj and obj.pk:
            count = obj.calls.count()
            return format_html('<strong>{}</strong> calls', count)
        return '0 calls'
    
    call_count.short_description = 'Total Calls'
    
    def activate_assistants(self, request, queryset):
        """Admin action to activate selected assistants"""
        updated = queryset.update(is_active=True)
        self.message_user(request, f'{updated} assistant(s) activated successfully.')
    
    activate_assistants.short_description = 'Activate selected assistants'
    
    def deactivate_assistants(self, request, queryset):
        """Admin action to deactivate selected assistants"""
        updated = queryset.update(is_active=False)
        self.message_user(request, f'{updated} assistant(s) deactivated successfully.')
    
    deactivate_assistants.short_description = 'Deactivate selected assistants'


@admin.register(UserAssistantPreference)
class UserAssistantPreferenceAdmin(admin.ModelAdmin):
    list_display = ['user', 'assistant', 'updated_at']
    list_filter = ['assistant', 'updated_at']
    search_fields = ['user__username', 'user__email', 'assistant__name']
    readonly_fields = ['updated_at']
    
    fieldsets = (
        ('Preference Information', {
            'fields': ('user', 'assistant', 'updated_at')
        }),
    )


@admin.register(CallPrompt)
class CallPromptAdmin(admin.ModelAdmin):
    list_display = ['name', 'is_active', 'is_default', 'created_by', 'created_at', 'updated_at']
    list_filter = ['is_active', 'is_default', 'created_at', 'updated_at']
    search_fields = ['name', 'description', 'prompt_template']
    readonly_fields = ['created_at', 'updated_at', 'preview_prompt']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'description', 'is_active', 'is_default', 'created_by'),
            'description': 'Set "Is Default" to use this prompt when no prompt is selected. Only one prompt can be default.'
        }),
        ('Prompt Template', {
            'fields': ('prompt_template', 'preview_prompt'),
            'description': 'Use placeholders: {senior_name}, {senior_age}, {interests}, {health_notes}, {call_purpose}, {conversation_context}'
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def preview_prompt(self, obj):
        """Show a preview of how the prompt will look with sample data"""
        if not obj or not obj.prompt_template:
            return format_html('<em>Enter a prompt template above to see a preview</em>')
        
        sample_data = {
            'senior_name': 'John Doe',
            'senior_age': '75',
            'interests': 'Gardening, Reading',
            'health_notes': 'Generally healthy',
            'call_purpose': 'general_checkin',
            'conversation_context': 'This is the first conversation with this person.'
        }
        
        try:
            preview = obj.prompt_template.format(**sample_data)
            return format_html('<pre style="max-height: 300px; overflow-y: auto; white-space: pre-wrap; background-color: #f8f9fa; padding: 10px; border-radius: 4px;">{}</pre>', preview)
        except KeyError as e:
            return format_html('<span style="color: red;">Error: Missing placeholder {}</span>', str(e))
        except Exception as e:
            return format_html('<span style="color: red;">Error: {}</span>', str(e))
    
    preview_prompt.short_description = 'Preview (with sample data)'
    
    def save_model(self, request, obj, form, change):
        """Set created_by to current user if not set and handle default prompt"""
        from .models import CallPrompt
        
        if not obj.created_by_id:
            obj.created_by = request.user
        
        # IMPORTANT: Unset all other defaults BEFORE saving
        # This must happen before super().save_model() which calls obj.save()
        if obj.is_default:
            # Get current PK (might be None for new objects)
            current_pk = obj.pk
            
            # Unset all other defaults first - this must complete before save()
            queryset = CallPrompt.objects.filter(is_default=True)
            if current_pk:
                queryset = queryset.exclude(pk=current_pk)
            queryset.update(is_default=False)
        
        # Now save the object
        # The model's save() method will also handle is_default as a safety net
        super().save_model(request, obj, form, change)


@admin.register(Call)
class CallAdmin(admin.ModelAdmin):
    list_display = ['senior', 'twilio_status', 'assistant', 'prompt', 'duration', 'created_at', 'initiated_by']
    list_filter = ['twilio_status', 'vapi_status', 'created_at', 'call_purpose', 'prompt', 'assistant']
    search_fields = ['senior__name', 'twilio_sid', 'vapi_call_id', 'prompt__name']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('Call Information', {
            'fields': ('senior', 'call_purpose', 'prompt', 'initiated_by')
        }),
        ('Twilio Details', {
            'fields': ('twilio_sid', 'twilio_status', 'duration', 'call_start_time', 'call_end_time')
        }),
        ('Vapi Details', {
            'fields': ('assistant', 'vapi_call_id', 'vapi_status', 'vapi_assistant_id')
        }),
        ('AI Configuration', {
            'fields': ('ai_prompt',),
            'classes': ('collapse',)
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )


@admin.register(CallLog)
class CallLogAdmin(admin.ModelAdmin):
    list_display = ['call', 'event_type', 'message', 'created_at']
    list_filter = ['event_type', 'created_at']
    search_fields = ['call__senior__name', 'message']
    readonly_fields = ['created_at']
    
    fieldsets = (
        ('Log Information', {
            'fields': ('call', 'event_type', 'message')
        }),
        ('Additional Data', {
            'fields': ('data',),
            'classes': ('collapse',)
        }),
        ('Timestamp', {
            'fields': ('created_at',)
        }),
    )