from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Avg
from .models import Survey

@admin.register(Survey)
class SurveyAdmin(admin.ModelAdmin):
    # List display configuration
    list_display = (
        'user',
        'created_at',
        'water_usage',
        'daily_consumption_awareness',
        'get_consciousness_score',
        'get_survey_status'
    )

    # Filtering options
    list_filter = (
        'created_at',
        'water_usage',
        'daily_consumption_awareness',
        'fix_leaks',
        'water_saving_appliances'
    )

    # Search configuration
    search_fields = (
        'user__username',
        'user__email',
        'biggest_cause_of_wastage',
        'resources_needed'
    )

    # Fields to display in detail view, grouped by category
    fieldsets = (
        ('User Information', {
            'fields': ('user',)
        }),
        ('General Awareness', {
            'fields': (
                'water_usage',
                'daily_consumption_awareness',
                'dripping_tap_wastage'
            )
        }),
        ('Personal Habits', {
            'fields': (
                'brushing_habits',
                'fix_leaks',
                'reuse_water',
                'water_saving_appliances'
            )
        }),
        ('Feedback and Suggestions', {
            'fields': (
                'biggest_cause_of_wastage',
                'resources_needed',
                'additional_suggestions'
            ),
            'classes': ('collapse',)  # Makes this section collapsible
        }),
        ('Metadata', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    # Read-only fields
    readonly_fields = ('created_at', 'updated_at')

    # Date hierarchy for drilling down
    date_hierarchy = 'created_at'

    # Ordering
    ordering = ('-created_at',)

    def get_consciousness_score(self, obj):
        """Display water consciousness score"""
        return f"{obj.get_water_consciousness_score()}%"
    get_consciousness_score.short_description = 'Consciousness Score'

    def get_survey_status(self, obj):
        """Display survey status based on consciousness score"""
        score = obj.get_water_consciousness_score()
        if score >= 75:
            return 'Excellent'
        elif score >= 50:
            return 'Good'
        else:
            return 'Needs Improvement'
    get_survey_status.short_description = 'Status'
