from django.contrib import admin
from django.utils.html import format_html
from django.utils import timezone
from .models import ContactForm


@admin.register(ContactForm)
class ContactFormAdmin(admin.ModelAdmin):
    """Admin interface for ContactForm model"""
    
    list_display = [
        'id',
        'name',
        'email',
        'subject_badge', 
        'status_badge',
        'is_recent_badge',
        'view_details_link',
        'created_at'
    ]
    
    list_filter = [
        'status',
        'subject',
        'created_at',
        'updated_at'
    ]
    
    search_fields = [
        'name',
        'email',
        'message',
        'phone'
    ]
    
    readonly_fields = [
        'id',
        'created_at',
        'updated_at',
        'is_recent',
        'view_full_details'
    ]
    
    list_per_page = 25
    
    fieldsets = (
        ('Contact Information', {
            'fields': ('name', 'email', 'phone')
        }),
        ('Inquiry Details', {
            'fields': ('subject', 'message')
        }),
        ('Status Management', {
            'fields': ('status', 'admin_notes', 'responded_by', 'responded_at'),
            'classes': ('collapse',)
        }),
        ('System Information', {
            'fields': ('id', 'created_at', 'updated_at', 'is_recent', 'view_full_details'),
            'classes': ('collapse',)
        }),
    )
    
    actions = [
        'mark_as_pending',
        'mark_as_in_progress', 
        'mark_as_resolved',
        'mark_as_closed',
        'view_selected_details'
    ]
    
    def subject_badge(self, obj):
        """Display subject as a colored badge"""
        colors = {
            'admission': '#3b82f6',  # blue
            'academics': '#10b981',  # green
            'fees': '#f59e0b',       # amber
            'career': '#8b5cf6',     # purple
            'other': '#6b7280',      # gray
        }
        color = colors.get(obj.subject, '#6b7280')
        return format_html(
            '<span style="background-color: {}; color: white; padding: 3px 8px; border-radius: 12px; font-size: 12px;">{}</span>',
            color,
            obj.get_subject_display()
        )
    subject_badge.short_description = 'Subject'
    subject_badge.admin_order_field = 'subject'
    
    def status_badge(self, obj):
        """Display status as a colored badge"""
        color = obj.get_status_color()
        return format_html(
            '<span style="background-color: {}; color: white; padding: 3px 8px; border-radius: 12px; font-size: 12px;">{}</span>',
            color,
            obj.get_status_display()
        )
    status_badge.short_description = 'Status'
    status_badge.admin_order_field = 'status'
    
    def is_recent_badge(self, obj):
        """Display a badge if the submission is recent"""
        if obj.is_recent():
            return format_html(
                '<span style="background-color: #ef4444; color: white; padding: 2px 6px; border-radius: 8px; font-size: 11px;">NEW</span>'
            )
        return ''
    is_recent_badge.short_description = 'Recent'
    
    def view_details_link(self, obj):
        """Display a link to view full contact details"""
        if obj.pk:
            return format_html(
                '<a href="/admin/contact/contactform/{}/change/" class="button" style="'
                'background-color: #417690; color: white; padding: 4px 8px; '
                'text-decoration: none; border-radius: 4px; font-size: 11px; '
                'display: inline-block;">📄 View Details</a>',
                obj.pk
            )
        return ''
    view_details_link.short_description = 'Actions'
    view_details_link.allow_tags = True
    
    def view_full_details(self, obj):
        """Display full contact information in a formatted way"""
        if not obj.pk:
            return "Not available for new records"
        
        contact_info = f"""
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 10px 0;">
            <h3 style="color: #495057; margin-top: 0;">📧 Contact Information</h3>
            <table style="width: 100%; border-collapse: collapse;">
                <tr><td style="padding: 5px; font-weight: bold; width: 120px;">Name:</td><td style="padding: 5px;">{obj.name}</td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Email:</td><td style="padding: 5px;"><a href="mailto:{obj.email}">{obj.email}</a></td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Phone:</td><td style="padding: 5px;">{obj.phone if obj.phone else 'Not provided'}</td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Subject:</td><td style="padding: 5px;"><span style="background-color: #e3f2fd; padding: 2px 6px; border-radius: 4px;">{obj.get_subject_display()}</span></td></tr>
            </table>
            
            <h4 style="color: #495057; margin: 15px 0 10px 0;">💬 Message</h4>
            <div style="background: white; padding: 10px; border-left: 4px solid #007bff; margin: 10px 0; white-space: pre-wrap;">{obj.message}</div>
            
            <h4 style="color: #495057; margin: 15px 0 10px 0;">📊 Status Information</h4>
            <table style="width: 100%; border-collapse: collapse;">
                <tr><td style="padding: 5px; font-weight: bold; width: 120px;">Status:</td><td style="padding: 5px;"><span style="background-color: {obj.get_status_color()}; color: white; padding: 2px 6px; border-radius: 4px;">{obj.get_status_display()}</span></td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Submitted:</td><td style="padding: 5px;">{obj.created_at.strftime('%B %d, %Y at %I:%M %p')}</td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Reference:</td><td style="padding: 5px; font-family: monospace; background: #f1f3f4; padding: 2px 6px; border-radius: 4px;">REF{obj.pk:06d}</td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Last Updated:</td><td style="padding: 5px;">{obj.updated_at.strftime('%B %d, %Y at %I:%M %p')}</td></tr>
            </table>
            
            {self._get_response_info(obj)}
            
            <div style="margin-top: 15px; padding: 10px; background: #fff3cd; border-radius: 4px; border: 1px solid #ffeaa7;">
                <strong>📞 Quick Actions:</strong>
                <a href="mailto:{obj.email}?subject=Re: {obj.get_subject_display()} - REF{obj.pk:06d}" style="margin-left: 10px; color: #007bff;">✉️ Reply via Email</a>
                <span style="margin-left: 10px;">📱 Call: {obj.phone if obj.phone else 'No phone provided'}</span>
            </div>
        </div>
        """
        return format_html(contact_info)
    view_full_details.short_description = 'Contact Details'
    view_full_details.allow_tags = True
    
    def _get_response_info(self, obj):
        """Helper method to generate response information HTML"""
        if obj.responded_at and obj.responded_by:
            return f"""
            <h4 style="color: #28a745; margin: 15px 0 10px 0;">✅ Response Information</h4>
            <table style="width: 100%; border-collapse: collapse;">
                <tr><td style="padding: 5px; font-weight: bold; width: 120px;">Responded By:</td><td style="padding: 5px;">{obj.responded_by}</td></tr>
                <tr><td style="padding: 5px; font-weight: bold;">Response Date:</td><td style="padding: 5px;">{obj.responded_at.strftime('%B %d, %Y at %I:%M %p')}</td></tr>
            </table>
            """
        elif obj.status == 'resolved':
            return f"""
            <h4 style="color: #ffc107; margin: 15px 0 10px 0;">⚠️ Response Information</h4>
            <p style="background: #fff3cd; padding: 8px; border-radius: 4px;">Status marked as resolved but no response details recorded.</p>
            """
        else:
            return f"""
            <h4 style="color: #6c757d; margin: 15px 0 10px 0;">⏳ Pending Response</h4>
            <p style="background: #f8f9fa; padding: 8px; border-radius: 4px;">This inquiry is awaiting response.</p>
            """
    
    def mark_as_pending(self, request, queryset):
        """Action to mark selected submissions as pending"""
        updated = queryset.update(status='pending')
        self.message_user(request, f'{updated} submissions marked as pending.')
    mark_as_pending.short_description = 'Mark selected as Pending'
    
    def mark_as_in_progress(self, request, queryset):
        """Action to mark selected submissions as in progress"""
        updated = queryset.update(status='in_progress')
        self.message_user(request, f'{updated} submissions marked as in progress.')
    mark_as_in_progress.short_description = 'Mark selected as In Progress'
    
    def mark_as_resolved(self, request, queryset):
        """Action to mark selected submissions as resolved"""
        updated = queryset.update(
            status='resolved',
            responded_at=timezone.now(),
            responded_by=request.user.get_full_name() or request.user.username
        )
        self.message_user(request, f'{updated} submissions marked as resolved.')
    mark_as_resolved.short_description = 'Mark selected as Resolved'
    
    def mark_as_closed(self, request, queryset):
        """Action to mark selected submissions as closed"""
        updated = queryset.update(status='closed')
        self.message_user(request, f'{updated} submissions marked as closed.')
    mark_as_closed.short_description = 'Mark selected as Closed'
    
    mark_as_closed.short_description = 'Mark selected as Closed'
    
    def view_selected_details(self, request, queryset):
        """Action to view detailed information for selected contacts"""
        if queryset.count() > 10:
            self.message_user(request, 'Please select 10 or fewer contacts to view details.', level='warning')
            return
        
        # Create a detailed summary message
        details = []
        for obj in queryset:
            detail = f"""
            📧 {obj.name} ({obj.email})
            📞 {obj.phone or 'No phone'}
            📋 {obj.get_subject_display()}
            📅 {obj.created_at.strftime('%Y-%m-%d %H:%M')}
            🔖 REF{obj.pk:06d}
            📊 {obj.get_status_display()}
            💬 {obj.message[:100]}{'...' if len(obj.message) > 100 else ''}
            """
            details.append(detail.strip())
        
        summary = f"""
        📋 Contact Details Summary ({queryset.count()} selected):
        
        """ + "\n\n" + "="*50 + "\n\n".join(details)
        
        # Use Django's message framework to display the summary
        self.message_user(
            request, 
            f'Details for {queryset.count()} contact(s) - Check individual contact pages for full information.',
            level='info'
        )
    view_selected_details.short_description = 'View Details of Selected Contacts'
    
    def get_queryset(self, request):
        """Optimize queryset for admin list view"""
        return super().get_queryset(request).select_related()
    
    class Media:
        css = {
            'all': ('admin/css/custom_contact_form.css',)
        }
        js = ('admin/js/contact_form.js',)
