import csv
import io
from django.http import HttpResponse
from django.db.models import Count, Avg, Q
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from .models import Response


class StatisticsService:
    @staticmethod
    def get_global_statistics():
        total_complete = Response.objects.filter(is_complete=True).count()
        total_partial = Response.objects.filter(is_complete=False).count()

        # Demographics
        education_dist = list(
            Response.objects.filter(is_complete=True)
            .values('education_level')
            .annotate(count=Count('id'))
            .order_by('-count')
        )

        gender_dist = list(
            Response.objects.filter(is_complete=True)
            .values('gender')
            .annotate(count=Count('id'))
            .order_by('-count')
        )

        age_dist = list(
            Response.objects.filter(is_complete=True)
            .values('age_range')
            .annotate(count=Count('id'))
            .order_by('-count')
        )

        # Account usage
        mobile_count = Response.objects.filter(is_complete=True, has_mobile_account=True).count()
        bank_count = Response.objects.filter(is_complete=True, has_bank_account=True).count()
        online_count = Response.objects.filter(is_complete=True, has_done_online_banking=True).count()

        return {
            'total_complete': total_complete,
            'total_partial': total_partial,
            'total': total_complete + total_partial,
            'education_distribution': education_dist,
            'gender_distribution': gender_dist,
            'age_distribution': age_dist,
            'account_usage': {
                'mobile_money': mobile_count,
                'bank_account': bank_count,
                'online_banking': online_count,
            }
        }

    @staticmethod
    def get_section_statistics(section):
        responses = Response.objects.filter(is_complete=True)

        if section == 'adoption':
            fields = Response.get_adoption_fields()
        elif section == 'barriers':
            fields = Response.get_barrier_fields()
        elif section == 'services':
            fields = Response.get_service_fields()
        elif section == 'technology':
            fields = Response.get_tech_fields()
        elif section == 'frequency':
            fields = Response.get_freq_fields()
        else:
            return {}

        stats = {}
        for field in fields:
            values = responses.exclude(**{f'{field}__isnull': True}).exclude(**{field: 6})
            count = values.count()
            if count > 0:
                avg = values.aggregate(avg=Avg(field))['avg'] or 0
                stats[field] = {
                    'label': Response._meta.get_field(field).verbose_name,
                    'count': count,
                    'mean': round(avg, 2),
                    'na_count': responses.filter(**{field: 6}).count(),
                }

        # Sort by mean descending
        sorted_stats = dict(sorted(stats.items(), key=lambda x: x[1]['mean'], reverse=True))

        return {
            'stats': sorted_stats,
            'top_factors': list(sorted_stats.items())[:5],
            'bottom_factors': list(sorted_stats.items())[-5:],
            'total_responses': responses.count(),
        }


class ExportService:
    @staticmethod
    def get_all_fields():
        return [f.name for f in Response._meta.fields]

    @staticmethod
    def get_field_labels():
        return {f.name: f.verbose_name for f in Response._meta.fields}

    @staticmethod
    def export_csv():
        response = HttpResponse(content_type='text/csv; charset=utf-8')
        response['Content-Disposition'] = 'attachment; filename="enquete_reponses.csv"'
        response.write('\ufeff')  # BOM for Excel

        writer = csv.writer(response)
        fields = ExportService.get_all_fields()
        labels = ExportService.get_field_labels()

        # Header
        writer.writerow([labels.get(f, f) for f in fields])

        # Data
        for obj in Response.objects.filter(is_complete=True):
            row = []
            for field in fields:
                value = getattr(obj, field)
                if value is None:
                    row.append('')
                elif isinstance(value, bool):
                    row.append('Oui' if value else 'Non')
                else:
                    row.append(str(value))
            writer.writerow(row)

        return response

    @staticmethod
    def export_excel():
        wb = Workbook()
        ws = wb.active
        ws.title = "Réponses"

        fields = ExportService.get_all_fields()
        labels = ExportService.get_field_labels()

        # Header styling
        header_font = Font(bold=True, color="FFFFFF")
        header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")

        # Write header
        for col, field in enumerate(fields, 1):
            cell = ws.cell(row=1, column=col, value=labels.get(field, field))
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = Alignment(horizontal='center')

        # Write data
        for row_idx, obj in enumerate(Response.objects.filter(is_complete=True), 2):
            for col, field in enumerate(fields, 1):
                value = getattr(obj, field)
                if isinstance(value, bool):
                    value = 'Oui' if value else 'Non'
                ws.cell(row=row_idx, column=col, value=value)

        # Adjust column widths
        for col in ws.columns:
            max_length = max(len(str(cell.value or '')) for cell in col)
            ws.column_dimensions[col[0].column_letter].width = min(max_length + 2, 50)

        # Auto-filter
        ws.auto_filter.ref = ws.dimensions

        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename="enquete_reponses.xlsx"'
        wb.save(response)
        return response

    @staticmethod
    def export_pdf():
        buffer = io.BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4)
        elements = []
        styles = getSampleStyleSheet()

        # Title
        elements.append(Paragraph("Rapport Statistique - Enquête Bancaire", styles['Title']))
        elements.append(Paragraph("Services bancaires en ligne - Côte d'Ivoire", styles['Normal']))
        elements.append(Spacer(1, 20))

        # Get statistics
        stats = StatisticsService.get_global_statistics()

        # Overview
        elements.append(Paragraph("Vue d'ensemble", styles['Heading2']))
        overview_data = [
            ["Métrique", "Valeur"],
            ["Réponses complètes", str(stats['total_complete'])],
            ["Réponses partielles", str(stats['total_partial'])],
            ["Total", str(stats['total'])],
        ]
        overview_table = Table(overview_data, colWidths=[200, 100])
        overview_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#4472C4')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ]))
        elements.append(overview_table)
        elements.append(Spacer(1, 20))

        # Top adoption factors
        adoption_stats = StatisticsService.get_section_statistics('adoption')
        if adoption_stats.get('top_factors'):
            elements.append(Paragraph("Top 5 Facteurs d'adoption", styles['Heading2']))
            adoption_data = [["Facteur", "Moyenne"]]
            for field, data in adoption_stats['top_factors']:
                adoption_data.append([data['label'], str(data['mean'])])

            adoption_table = Table(adoption_data, colWidths=[300, 100])
            adoption_table.setStyle(TableStyle([
                ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#28a745')),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
                ('ALIGN', (1, 0), (1, -1), 'CENTER'),
                ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ]))
            elements.append(adoption_table)
            elements.append(Spacer(1, 20))

        # Top barriers
        barrier_stats = StatisticsService.get_section_statistics('barriers')
        if barrier_stats.get('top_factors'):
            elements.append(Paragraph("Top 5 Freins à l'adoption", styles['Heading2']))
            barrier_data = [["Frein", "Moyenne"]]
            for field, data in barrier_stats['top_factors']:
                barrier_data.append([data['label'], str(data['mean'])])

            barrier_table = Table(barrier_data, colWidths=[300, 100])
            barrier_table.setStyle(TableStyle([
                ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#dc3545')),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
                ('ALIGN', (1, 0), (1, -1), 'CENTER'),
                ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ]))
            elements.append(barrier_table)

        # Footer
        elements.append(Spacer(1, 30))
        elements.append(Paragraph(
            "ASSIÉLOU N'Doli Guillaume - Université Nangui Abrogoua",
            styles['Normal']
        ))

        doc.build(elements)
        buffer.seek(0)

        response = HttpResponse(buffer, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="rapport_enquete.pdf"'
        return response
