"""
Minimal Analytics Dashboard View - Guaranteed to Work
"""

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.utils import timezone
from django.db.models import Sum, Count, Q, Avg
from datetime import datetime, timedelta
from decimal import Decimal

@login_required
def analytics_dashboard(request):
    """Minimal analytics dashboard that always works"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Import models
        from .models import Loan, LoanProduct
        from users.models import CustomUser
        
        # Get basic statistics with simple queries
        loans_qs = Loan.objects.all()
        if selected_branch_id:
            loans_qs = loans_qs.filter(borrower__branch_id=selected_branch_id)
        
        # Basic loan metrics
        total_loans = loans_qs.count()
        active_loans = loans_qs.filter(status='active').count()
        total_disbursed = loans_qs.aggregate(total=Sum('principal_amount'))['total'] or 0
        
        # Calculate total collected from repayments (amount_paid is a property, not a field)
        from .models import Repayment
        total_collected = Repayment.objects.filter(
            loan__in=loans_qs
        ).aggregate(total=Sum('amount'))['total'] or 0
        
        # Basic client metrics
        clients_qs = CustomUser.objects.filter(role='borrower')
        if selected_branch_id:
            clients_qs = clients_qs.filter(branch_id=selected_branch_id)
        
        total_clients = clients_qs.count()
        active_clients = clients_qs.filter(loans__status='active').distinct().count()
        
        # Create simple statistics structure
        loan_stats = {
            'basic_metrics': {
                'active_loans': {'current': active_loans},
                'total_disbursed': {'current': total_disbursed},
                'total_collected': {'current': total_collected},
            },
            'performance_metrics': {
                'collection_rate': {'current': 0},
                'default_rate': {'current': 0},
                'on_time_payment_rate': {'current': 0},
            }
        }
        
        client_stats = {
            'basic_metrics': {
                'active_clients': {'current': active_clients},
                'total_clients': {'current': total_clients},
                'clients_with_loans': {'current': active_clients},
            },
            'performance_metrics': {
                'loan_uptake_rate': (active_clients / total_clients * 100) if total_clients > 0 else 0
            }
        }
        
        payment_stats = {
            'basic_metrics': {
                'total_transactions': {'current': total_collected},
            }
        }
        
        # Get available filters
        loan_products = LoanProduct.objects.filter(is_active=True)
        borrowers = clients_qs[:100]  # Limit for performance
        
        context = {
            'loan_stats': loan_stats,
            'client_stats': client_stats,
            'payment_stats': payment_stats,
            'loan_products': loan_products,
            'borrowers': borrowers,
            'today': timezone.now().date(),
        }
        
        return render(request, 'loans/analytics_dashboard.html', context)
        
    except Exception as e:
        # Fallback with empty data
        context = {
            'loan_stats': {
                'basic_metrics': {
                    'active_loans': {'current': 0},
                    'total_disbursed': {'current': 0},
                },
                'performance_metrics': {
                    'collection_rate': {'current': 0},
                    'default_rate': {'current': 0},
                    'on_time_payment_rate': {'current': 0},
                }
            },
            'client_stats': {
                'basic_metrics': {
                    'active_clients': {'current': 0},
                    'total_clients': {'current': 0},
                    'clients_with_loans': {'current': 0},
                },
                'performance_metrics': {
                    'loan_uptake_rate': 0
                }
            },
            'payment_stats': {
                'basic_metrics': {
                    'total_transactions': {'current': 0},
                }
            },
            'loan_products': [],
            'borrowers': [],
            'today': timezone.now().date(),
        }
        
        return render(request, 'loans/analytics_dashboard.html', context)


# PDF generation functions using reportlab
@login_required
def generate_loans_dashboard_pdf(request):
    """Generate comprehensive PDF report for loans dashboard"""
    try:
        from reportlab.lib.pagesizes import letter, A4
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, PageBreak
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
        from io import BytesIO
        
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Get data
        from .models import Loan, LoanProduct
        from users.models import CustomUser
        
        loans_qs = Loan.objects.all()
        if selected_branch_id:
            loans_qs = loans_qs.filter(borrower__branch_id=selected_branch_id)
        
        # Calculate metrics
        total_loans = loans_qs.count()
        active_loans = loans_qs.filter(status='active').count()
        completed_loans = loans_qs.filter(status='completed').count()
        defaulted_loans = loans_qs.filter(status='defaulted').count()
        total_disbursed = loans_qs.aggregate(total=Sum('principal_amount'))['total'] or Decimal('0')
        
        # Calculate total collected from repayments (amount_paid is a property, not a field)
        from .models import Repayment
        total_collected = Repayment.objects.filter(
            loan__in=loans_qs
        ).aggregate(total=Sum('amount'))['total'] or Decimal('0')
        
        outstanding = total_disbursed - total_collected
        
        # Create PDF
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
        
        # Container for PDF elements
        elements = []
        
        # Styles
        styles = getSampleStyleSheet()
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Heading1'],
            fontSize=24,
            textColor=colors.HexColor('#2c3e50'),
            spaceAfter=30,
            alignment=TA_CENTER
        )
        heading_style = ParagraphStyle(
            'CustomHeading',
            parent=styles['Heading2'],
            fontSize=16,
            textColor=colors.HexColor('#34495e'),
            spaceAfter=12,
            spaceBefore=12
        )
        
        # Title
        elements.append(Paragraph("Loans Dashboard Report", title_style))
        elements.append(Paragraph(f"Generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}", styles['Normal']))
        elements.append(Spacer(1, 0.3*inch))
        
        # Summary Section
        elements.append(Paragraph("Executive Summary", heading_style))
        summary_data = [
            ['Metric', 'Value'],
            ['Total Loans', str(total_loans)],
            ['Active Loans', str(active_loans)],
            ['Completed Loans', str(completed_loans)],
            ['Defaulted Loans', str(defaulted_loans)],
            ['Total Disbursed', f'KES {total_disbursed:,.2f}'],
            ['Total Collected', f'KES {total_collected:,.2f}'],
            ['Outstanding Balance', f'KES {outstanding:,.2f}'],
        ]
        
        summary_table = Table(summary_data, colWidths=[3*inch, 3*inch])
        summary_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#3498db')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 12),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 1), (-1, -1), 10),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
        ]))
        elements.append(summary_table)
        elements.append(Spacer(1, 0.3*inch))
        
        # Loan Status Breakdown
        elements.append(Paragraph("Loan Status Distribution", heading_style))
        status_data = [
            ['Status', 'Count', 'Percentage'],
            ['Active', str(active_loans), f'{(active_loans/total_loans*100) if total_loans > 0 else 0:.1f}%'],
            ['Completed', str(completed_loans), f'{(completed_loans/total_loans*100) if total_loans > 0 else 0:.1f}%'],
            ['Defaulted', str(defaulted_loans), f'{(defaulted_loans/total_loans*100) if total_loans > 0 else 0:.1f}%'],
        ]
        
        status_table = Table(status_data, colWidths=[2*inch, 2*inch, 2*inch])
        status_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#2ecc71')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 11),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 1), (-1, -1), 10),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
        ]))
        elements.append(status_table)
        elements.append(Spacer(1, 0.3*inch))
        
        # Recent Loans
        elements.append(Paragraph("Recent Loans (Last 10)", heading_style))
        recent_loans = loans_qs.order_by('-created_at')[:10]
        
        if recent_loans.exists():
            loan_data = [['Loan #', 'Borrower', 'Amount', 'Status', 'Date']]
            for loan in recent_loans:
                loan_data.append([
                    loan.loan_number or 'N/A',
                    loan.borrower.get_full_name() if loan.borrower else 'N/A',
                    f'KES {loan.principal_amount:,.0f}',
                    loan.status.title(),
                    loan.created_at.strftime('%Y-%m-%d')
                ])
            
            loan_table = Table(loan_data, colWidths=[1.2*inch, 1.8*inch, 1.3*inch, 1.2*inch, 1.2*inch])
            loan_table.setStyle(TableStyle([
                ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#e74c3c')),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('FONTSIZE', (0, 0), (-1, 0), 10),
                ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
                ('FONTSIZE', (0, 1), (-1, -1), 8),
                ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
            ]))
            elements.append(loan_table)
        else:
            elements.append(Paragraph("No recent loans found.", styles['Normal']))
        
        # Build PDF
        doc.build(elements)
        
        # Get PDF data
        pdf_data = buffer.getvalue()
        buffer.close()
        
        # Return response
        response = HttpResponse(pdf_data, content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="loans_dashboard_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
        return response
        
    except Exception as e:
        # Fallback to text if PDF generation fails
        content = f"Loans Dashboard Report - Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\nError generating PDF: {str(e)}"
        response = HttpResponse(content, content_type='text/plain')
        response['Content-Disposition'] = f'attachment; filename="loans_report_{datetime.now().strftime("%Y%m%d")}.txt"'
        return response

@login_required
def generate_clients_dashboard_pdf(request):
    """Generate comprehensive PDF report for clients dashboard"""
    try:
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.enums import TA_CENTER
        from io import BytesIO
        
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Get data
        from users.models import CustomUser
        
        clients_qs = CustomUser.objects.filter(role='borrower')
        if selected_branch_id:
            clients_qs = clients_qs.filter(branch_id=selected_branch_id)
        
        # Calculate metrics
        total_clients = clients_qs.count()
        active_clients = clients_qs.filter(is_active=True).count()
        inactive_clients = total_clients - active_clients
        clients_with_loans = clients_qs.filter(loans__isnull=False).distinct().count()
        
        # Create PDF
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
        elements = []
        
        styles = getSampleStyleSheet()
        title_style = ParagraphStyle('CustomTitle', parent=styles['Heading1'], fontSize=24, 
                                     textColor=colors.HexColor('#2c3e50'), spaceAfter=30, alignment=TA_CENTER)
        
        elements.append(Paragraph("Clients Dashboard Report", title_style))
        elements.append(Paragraph(f"Generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}", styles['Normal']))
        elements.append(Spacer(1, 0.3*inch))
        
        # Summary
        summary_data = [
            ['Metric', 'Value'],
            ['Total Clients', str(total_clients)],
            ['Active Clients', str(active_clients)],
            ['Inactive Clients', str(inactive_clients)],
            ['Clients with Loans', str(clients_with_loans)],
        ]
        
        summary_table = Table(summary_data, colWidths=[3*inch, 3*inch])
        summary_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#3498db')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
        ]))
        elements.append(summary_table)
        
        doc.build(elements)
        pdf_data = buffer.getvalue()
        buffer.close()
        
        response = HttpResponse(pdf_data, content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="clients_dashboard_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
        return response
        
    except Exception as e:
        content = f"Clients Dashboard Report - Error: {str(e)}"
        response = HttpResponse(content, content_type='text/plain')
        response['Content-Disposition'] = f'attachment; filename="clients_report_{datetime.now().strftime("%Y%m%d")}.txt"'
        return response

@login_required
def generate_payments_dashboard_pdf(request):
    """Generate comprehensive PDF report for payments dashboard"""
    try:
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.enums import TA_CENTER
        from io import BytesIO
        from payments.models import MpesaTransaction
        
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Get data
        transactions_qs = MpesaTransaction.objects.filter(result_code='0')
        if selected_branch_id:
            transactions_qs = transactions_qs.filter(loan__borrower__branch_id=selected_branch_id)
        
        total_transactions = transactions_qs.count()
        total_amount = transactions_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0')
        
        # Create PDF
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
        elements = []
        
        styles = getSampleStyleSheet()
        title_style = ParagraphStyle('CustomTitle', parent=styles['Heading1'], fontSize=24,
                                     textColor=colors.HexColor('#2c3e50'), spaceAfter=30, alignment=TA_CENTER)
        
        elements.append(Paragraph("Payments Dashboard Report", title_style))
        elements.append(Paragraph(f"Generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}", styles['Normal']))
        elements.append(Spacer(1, 0.3*inch))
        
        summary_data = [
            ['Metric', 'Value'],
            ['Total Transactions', str(total_transactions)],
            ['Total Amount', f'KES {total_amount:,.2f}'],
        ]
        
        summary_table = Table(summary_data, colWidths=[3*inch, 3*inch])
        summary_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#3498db')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.lightgrey]),
        ]))
        elements.append(summary_table)
        
        doc.build(elements)
        pdf_data = buffer.getvalue()
        buffer.close()
        
        response = HttpResponse(pdf_data, content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="payments_dashboard_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
        return response
        
    except Exception as e:
        content = f"Payments Dashboard Report - Error: {str(e)}"
        response = HttpResponse(content, content_type='text/plain')
        response['Content-Disposition'] = f'attachment; filename="payments_report_{datetime.now().strftime("%Y%m%d")}.txt"'
        return response

@login_required
def generate_reports_dashboard_pdf(request):
    """Generate PDF report for reports dashboard"""
    try:
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Paragraph
        from reportlab.lib.styles import getSampleStyleSheet
        from io import BytesIO
        
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4)
        elements = []
        styles = getSampleStyleSheet()
        
        elements.append(Paragraph("Reports Dashboard", styles['Title']))
        elements.append(Paragraph(f"Generated on {datetime.now().strftime('%B %d, %Y')}", styles['Normal']))
        
        doc.build(elements)
        pdf_data = buffer.getvalue()
        buffer.close()
        
        response = HttpResponse(pdf_data, content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="reports_dashboard_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
        return response
    except Exception as e:
        return HttpResponse(f"Error: {str(e)}", content_type='text/plain')

@login_required
def generate_portfolio_dashboard_pdf(request):
    """Generate PDF report for portfolio dashboard"""
    try:
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Paragraph
        from reportlab.lib.styles import getSampleStyleSheet
        from io import BytesIO
        
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4)
        elements = []
        styles = getSampleStyleSheet()
        
        elements.append(Paragraph("Portfolio Dashboard", styles['Title']))
        elements.append(Paragraph(f"Generated on {datetime.now().strftime('%B %d, %Y')}", styles['Normal']))
        
        doc.build(elements)
        pdf_data = buffer.getvalue()
        buffer.close()
        
        response = HttpResponse(pdf_data, content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="portfolio_dashboard_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
        return response
    except Exception as e:
        return HttpResponse(f"Error: {str(e)}", content_type='text/plain')

@login_required
def generate_custom_analytics_pdf(request):
    """Generate PDF report for custom analytics"""
    try:
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Paragraph
        from reportlab.lib.styles import getSampleStyleSheet
        from io import BytesIO
        
        buffer = BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4)
        elements = []
        styles = getSampleStyleSheet()
        
        elements.append(Paragraph("Custom Analytics Report", styles['Title']))
        elements.append(Paragraph(f"Generated on {datetime.now().strftime('%B %d, %Y')}", styles['Normal']))
        
        doc.build(elements)
        pdf_data = buffer.getvalue()
        buffer.close()
        
        response = HttpResponse(pdf_data, content_type='application/pdf')
        response['Content-Disposition'] = f'attachment; filename="custom_analytics_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
        return response
    except Exception as e:
        return HttpResponse(f"Error: {str(e)}", content_type='text/plain')
