from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Avg
from django.urls import path
from django.shortcuts import render
from django.http import HttpResponse
from .models import Response
from .services import StatisticsService, ExportService


@admin.register(Response)
class ResponseAdmin(admin.ModelAdmin):
    list_display = ['id', 'created_at', 'is_complete', 'education_level', 'gender', 'age_range', 'status_badge']
    list_filter = ['is_complete', 'education_level', 'gender', 'age_range', 'created_at']
    search_fields = ['contact_email', 'job_function', 'final_comment']
    readonly_fields = ['created_at', 'completed_at']
    date_hierarchy = 'created_at'

    fieldsets = (
        ('Informations', {
            'fields': ('created_at', 'completed_at', 'is_complete')
        }),
        ('Section A - Profil', {
            'fields': ('education_level', 'gender', 'job_function', 'age_range'),
            'classes': ('collapse',)
        }),
        ('Section B - Comptes', {
            'fields': ('has_done_online_banking', 'has_mobile_account', 'has_bank_account', 'other_account_type'),
            'classes': ('collapse',)
        }),
        ('Section C - Fréquence', {
            'fields': ('freq_mobile_account', 'freq_bank_account', 'freq_other_account'),
            'classes': ('collapse',)
        }),
        ('Section D - Technologies', {
            'fields': ('tech_landline', 'tech_smartphone', 'tech_computer', 'tech_tablet', 'tech_third_party_apps', 'tech_other', 'tech_other_freq'),
            'classes': ('collapse',)
        }),
        ('Section E - Services', {
            'fields': (
                'service_send_money', 'service_receive_money', 'service_withdraw', 'service_deposit',
                'service_auto_deposit', 'service_bill_payment', 'service_purchase', 'service_sell',
                'service_balance', 'service_transfer', 'service_check_deposit', 'service_transaction_monitoring',
                'service_messages', 'service_documents', 'service_alerts', 'service_chatbot', 'service_support'
            ),
            'classes': ('collapse',)
        }),
        ('Section F - Facteurs d\'adoption', {
            'fields': (
                'adopt_ease_of_use', 'adopt_ict_access', 'adopt_website_access', 'adopt_training',
                'adopt_tech_support', 'adopt_internet_reliability', 'adopt_internet_cost', 'adopt_security',
                'adopt_awareness', 'adopt_legal_framework', 'adopt_transaction_cost'
            ),
            'classes': ('collapse',)
        }),
        ('Section F - Freins', {
            'fields': (
                'barrier_security', 'barrier_cybercrime', 'barrier_trust', 'barrier_information',
                'barrier_time', 'barrier_skills', 'barrier_network_reliability', 'barrier_perceived_risk',
                'barrier_perceived_usefulness', 'barrier_limited_availability', 'barrier_ict_familiarity',
                'barrier_limited_activities', 'barrier_language', 'barrier_resistance_change',
                'barrier_legal_deficiency', 'barrier_complexity', 'barrier_past_experience',
                'barrier_traditional_attachment'
            ),
            'classes': ('collapse',)
        }),
        ('Section G - Commentaires', {
            'fields': ('final_comment', 'contact_email'),
            'classes': ('collapse',)
        }),
    )

    def status_badge(self, obj):
        if obj.is_complete:
            return format_html('<span style="color: #28a745;">✓ Complet</span>')
        return format_html('<span style="color: #ffc107;">⏳ Partiel</span>')
    status_badge.short_description = 'Statut'


class SurveyAdminSite(admin.AdminSite):
    site_header = 'Administration - Sondage Bancaire'
    site_title = 'Sondage CI'
    index_title = 'Tableau de bord'

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('statistics/', self.admin_view(self.statistics_view), name='statistics'),
            path('exports/', self.admin_view(self.exports_view), name='exports'),
            path('export/csv/', self.admin_view(self.export_csv), name='export_csv'),
            path('export/excel/', self.admin_view(self.export_excel), name='export_excel'),
            path('export/pdf/', self.admin_view(self.export_pdf), name='export_pdf'),
        ]
        return custom_urls + urls

    def statistics_view(self, request):
        stats = StatisticsService.get_global_statistics()
        adoption_stats = StatisticsService.get_section_statistics('adoption')
        barrier_stats = StatisticsService.get_section_statistics('barriers')

        context = {
            **self.each_context(request),
            'title': 'Statistiques',
            'stats': stats,
            'adoption_stats': adoption_stats,
            'barrier_stats': barrier_stats,
        }
        return render(request, 'admin/statistics.html', context)

    def exports_view(self, request):
        context = {
            **self.each_context(request),
            'title': 'Exports',
            'total_responses': Response.objects.filter(is_complete=True).count(),
        }
        return render(request, 'admin/exports.html', context)

    def export_csv(self, request):
        return ExportService.export_csv()

    def export_excel(self, request):
        return ExportService.export_excel()

    def export_pdf(self, request):
        return ExportService.export_pdf()
