from django.contrib import admin
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.contrib import messages
from django.urls import path, reverse
from django.http import HttpResponseRedirect
import json
from .models import liuyao


def generate_ai_analysis(modeladmin, request, queryset):
    """Admin action to generate AI analysis for selected LiuYao entries"""
    for entry in queryset:
        try:
            # Import here to avoid circular imports
            from ai.utils.liuyao_analysis import analyze_liuyao
            analyze_liuyao(entry)
        except Exception as e:
            modeladmin.message_user(request, f"Error generating analysis for {entry.question}: {str(e)}")
    modeladmin.message_user(request, f"Analysis requested for {queryset.count()} LiuYao entries")
generate_ai_analysis.short_description = "Generate AI analysis"


@admin.register(liuyao)
class LiuYaoAdmin(admin.ModelAdmin):
    list_display = ('question', 'user_display', 'qdate', 'created_at', 'analysis_status_display', 'report_status_display')
    list_filter = ('created_at', 'qdate', 'analysis_status', 'report_status', 'analysis_reported')
    search_fields = ('question', 'user__first_name', 'user__last_name', 'user__phone', 'report_message')
    readonly_fields = ('created_at', 'last_modified_at', 'uuid', 'analysis_timestamp', 'report_timestamp', 'report_resolved_by', 'report_resolved_at', 'ai_analysis_display', 'reset_ai_analysis_button')
    actions = [generate_ai_analysis, 'resolve_reports']
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('question', 'user', 'qdate', 'uuid')
        }),
        ('Hexagram Data', {
            'fields': ('y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'data')
        }),
        ('Analysis & Reading', {
            'fields': ('reading', 'feedback', 'analysis_status', 'analysis_timestamp', 'ai_analysis_display', 'reset_ai_analysis_button')
        }),
        ('Reports', {
            'fields': ('analysis_reported', 'report_category', 'report_message', 'report_timestamp', 'report_status', 'report_admin_notes', 'report_resolved_at'),
            'classes': ('collapse',)
        }),
        ('System', {
            'fields': ('created_at', 'last_modified_at')
        }),
    )
    
    def user_display(self, obj):
        """Display the user's name and phone number"""
        if not obj.user:
            return 'Guest User'
        
        # Get user's full name
        full_name = f"{obj.user.first_name} {obj.user.last_name}".strip()
        if not full_name:
            full_name = "No Name"
        
        return format_html(
            '<strong>{}</strong><br><small style="color: #666;">{}</small>',
            full_name,
            obj.user.phone
        )
    user_display.short_description = 'User'
    user_display.admin_order_field = 'user__first_name'
    
    def analysis_status_display(self, obj):
        """Format the analysis status with colors"""
        if obj.analysis_status == 'completed':
            return format_html('<span style="color: green;">✓ Completed</span>')
        elif obj.analysis_status == 'pending':
            return format_html('<span style="color: orange;">⟳ Pending</span>')
        elif obj.analysis_status == 'error':
            return format_html('<span style="color: red;">✗ Error</span>')
        else:
            return 'Not Analyzed'
    analysis_status_display.short_description = 'Analysis Status'
    
    def report_status_display(self, obj):
        """Display report status with color coding"""
        if not obj.analysis_reported:
            return format_html('<span style="color: #666;">无举报</span>')
        
        status = obj.report_status
        if status == 'pending':
            return format_html('<span style="color: orange; font-weight: bold;">⏳ 待处理</span>')
        elif status == 'reviewed':
            return format_html('<span style="color: blue; font-weight: bold;">👁️ 已审核</span>')
        elif status == 'resolved':
            return format_html('<span style="color: green; font-weight: bold;">✅ 已解决</span>')
        elif status == 'dismissed':
            return format_html('<span style="color: gray; font-weight: bold;">❌ 已忽略</span>')
        else:
            return format_html('<span style="color: red;">🚩 已举报</span>')
    report_status_display.short_description = '举报状态'
    
    def ai_analysis_display(self, obj):
        """Format the AI analysis in a readable way"""
        if not obj.ai_analysis:
            return 'No analysis available'
        
        try:
            analysis_data = obj.ai_analysis
            
            # Get the analysis content - try different possible keys
            analysis_content = (
                analysis_data.get('liuyao_analysis', '') or 
                analysis_data.get('analysis', '') or 
                analysis_data.get('response', '')
            )
            provider = analysis_data.get('provider', 'Unknown')
            model = analysis_data.get('model', 'Unknown')
            prompt = analysis_data.get('prompt', '')
            thinking = analysis_data.get('think', '')
            timestamp = obj.analysis_timestamp.strftime('%Y-%m-%d %H:%M:%S') if obj.analysis_timestamp else 'Unknown'
            
            html_sections = []
            
            # Add the main analysis content
            if analysis_content:
                # Truncate content for admin display
                if len(analysis_content) > 500:
                    display_content = analysis_content[:500] + '...'
                else:
                    display_content = analysis_content
                
                html_sections.append(f"""
                    <div style="margin-bottom: 15px; padding: 10px; border-left: 3px solid #007cba; background-color: #f8f9fa;">
                        <h4 style="margin: 0 0 8px 0; color: #007cba; font-size: 14px;">六爻分析</h4>
                        <div style="font-size: 12px; line-height: 1.4;">{display_content}</div>
                    </div>
                """)
            
            # Add thinking process if available
            if thinking:
                thinking_display = thinking[:300] + '...' if len(thinking) > 300 else thinking
                html_sections.append(f"""
                    <div style="margin-bottom: 15px; padding: 10px; border-left: 3px solid #6f42c1; background-color: #f8f9fa;">
                        <h4 style="margin: 0 0 8px 0; color: #6f42c1; font-size: 14px;">分析思路</h4>
                        <div style="font-size: 12px; line-height: 1.4;">{thinking_display}</div>
                    </div>
                """)
            
            # Build the complete HTML
            metadata_html = f"""
                <div style="background-color: #f8f9fa; padding: 10px; margin-top: 10px; border-radius: 4px; border-left: 3px solid #007cba;">
                    <small style="color: #666;">
                        <strong>Provider:</strong> {provider}<br>
                        <strong>Model:</strong> {model}<br>
                        <strong>Generated:</strong> {timestamp}
                    </small>
                </div>
            """
            
            return mark_safe(f'<div style="max-width: 600px;">{"".join(html_sections)}{metadata_html}</div>')
            
        except Exception as e:
            return format_html('<span style="color: red;">Error displaying analysis: {}</span>', str(e))
    
    ai_analysis_display.short_description = 'AI Analysis'
    
    def get_urls(self):
        """Add custom URLs for the reset functionality."""
        urls = super().get_urls()
        custom_urls = [
            path(
                '<int:liuyao_id>/reset-ai-analysis/',
                self.admin_site.admin_view(self.reset_ai_analysis_view),
                name='liuyao_reset_ai_analysis',
            ),
        ]
        return custom_urls + urls
    
    def reset_ai_analysis_view(self, request, liuyao_id):
        """Custom view to handle AI analysis reset for individual liuyao entry."""
        try:
            liuyao_entry = liuyao.objects.get(id=liuyao_id)
        except liuyao.DoesNotExist:
            messages.error(request, f"LiuYao entry with ID {liuyao_id} does not exist.")
            return HttpResponseRedirect(reverse('admin:liuyao_liuyao_changelist'))
        
        # Reset the AI analysis
        liuyao_entry.ai_analysis = None
        liuyao_entry.analysis_timestamp = None
        liuyao_entry.analysis_status = None
        liuyao_entry.save(update_fields=['ai_analysis', 'analysis_timestamp', 'analysis_status'])
        
        messages.success(request, f"AI analysis reset for LiuYao entry. You can now regenerate the analysis.")
        
        # Redirect back to the liuyao entry's change page
        return HttpResponseRedirect(reverse('admin:liuyao_liuyao_change', args=[liuyao_id]))
    
    def reset_ai_analysis_button(self, obj):
        """Display a reset button for AI analysis on the individual liuyao entry's change page."""
        if not obj.pk:  # New object, no reset needed
            return "Save the LiuYao entry first to enable AI analysis reset."
        
        if not obj.ai_analysis:
            return format_html(
                '<span style="color: #666; font-style: italic;">No AI analysis to reset</span>'
            )
        
        reset_url = reverse('admin:liuyao_reset_ai_analysis', args=[obj.pk])
        return format_html(
            '<a href="{}" class="button" style="background-color: #dc3545; color: white; padding: 8px 12px; '
            'text-decoration: none; border-radius: 4px; font-size: 13px; display: inline-block; margin-top: 5px;" '
            'onclick="return confirm(\'Are you sure you want to reset the AI analysis for this LiuYao entry? This will clear all analysis data and allow regeneration.\');">'
            '🗑️ Reset AI Analysis</a>',
            reset_url
        )
    reset_ai_analysis_button.short_description = 'Reset AI Analysis'
    
    def save_model(self, request, obj, form, change):
        """Override save_model to send email notifications when report status changes"""
        from django.utils import timezone
        
        # Check if report checkbox was unchecked (reset scenario)
        if change and 'analysis_reported' in form.changed_data:
            old_reported = form.initial.get('analysis_reported', False)
            new_reported = form.cleaned_data.get('analysis_reported', False)
            
            # If checkbox was unchecked, reset the email flag
            if old_reported and not new_reported:
                obj.report_resolution_email_sent = False
                self.message_user(request, "LiuYao report reset - email flag cleared for new report")
        
        # Check if this is a report status change
        if change and 'report_status' in form.changed_data:
            old_status = form.initial.get('report_status', '')
            new_status = form.cleaned_data.get('report_status', '')
            
            # Set resolver and timestamp for both resolved and dismissed
            if new_status in ['resolved', 'dismissed']:
                obj.report_resolved_by = request.user
                obj.report_resolved_at = timezone.now()
            
            # If status changed to resolved (send email only once per report)
            if new_status == 'resolved' and not obj.report_resolution_email_sent:
                # Send notification email to user
                try:
                    from api.utils import send_user_resolution_notification
                    if obj.user and obj.user.email:
                        send_user_resolution_notification(
                            obj.user, obj, 'liuyao', new_status, obj.report_admin_notes
                        )
                        obj.report_resolution_email_sent = True
                        self.message_user(request, f"Email notification sent to {obj.user.email}")
                except Exception as e:
                    self.message_user(request, f"Report status updated but email failed: {str(e)}")
        
        # Call the parent save_model
        super().save_model(request, obj, form, change)
    
    def resolve_reports(self, request, queryset):
        """Admin action to mark reports as resolved"""
        from django.utils import timezone
        updated = 0
        for entry in queryset.filter(analysis_reported=True, report_status='pending'):
            entry.report_status = 'resolved'
            entry.report_resolved_by = request.user
            entry.report_resolved_at = timezone.now()
            
            # Send notification email to user (only if not already sent)
            if not entry.report_resolution_email_sent:
                try:
                    from api.utils import send_user_resolution_notification
                    if entry.user and entry.user.email:
                        send_user_resolution_notification(
                            entry.user, entry, 'liuyao', 'resolved', entry.report_admin_notes
                        )
                        entry.report_resolution_email_sent = True
                except Exception as e:
                    self.message_user(request, f"Report resolved but email failed for {entry.question}: {str(e)}")
            
            entry.save(update_fields=[
                'report_status',
                'report_resolved_by', 'report_resolved_at',
                'report_resolution_email_sent'
            ])
            updated += 1
        
        self.message_user(request, f"已解决 {updated} 个六爻分析举报")
    resolve_reports.short_description = "解决选中的举报"
