
from django.http import HttpResponse
from django.template.loader import get_template
from django.utils import timezone
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.graphics.shapes import Drawing, Rect
from decimal import Decimal
import calendar
import io

def generate_expense_report_pdf(expenses, filters=None):
    """Generate a PDF report for expenses"""
    buffer = io.BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4)
    
    # Get styles
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=18,
        spaceAfter=30,
        alignment=1,  # Center alignment
    )
    
    heading_style = ParagraphStyle(
        'CustomHeading',
        parent=styles['Heading2'],
        fontSize=14,
        spaceAfter=12,
    )
    
    # Build story
    story = []
    
    # Title
    story.append(Paragraph("Expense Report", title_style))
    story.append(Spacer(1, 12))
    
    # Report details
    report_date = timezone.now().strftime("%B %d, %Y")
    story.append(Paragraph(f"Generated on: {report_date}", styles['Normal']))
    
    if filters:
        filter_text = "Filters Applied: "
        filter_parts = []
        if filters.get('month'):
            filter_parts.append(f"Month: {filters['month']}")
        if filters.get('year'):
            filter_parts.append(f"Year: {filters['year']}")
        if filters.get('category'):
            filter_parts.append(f"Category: {filters['category']}")
        if filters.get('employee'):
            filter_parts.append(f"Employee: {filters['employee']}")
        
        if filter_parts:
            filter_text += ", ".join(filter_parts)
            story.append(Paragraph(filter_text, styles['Normal']))
    
    story.append(Spacer(1, 20))
    
    # Summary statistics
    total_amount = sum(expense.amount for expense in expenses)
    total_count = len(expenses)
    
    summary_data = [
        ['Total Expenses:', str(total_count)],
        ['Total Amount:', f'KSh {total_amount:,.2f}'],
    ]
    
    summary_table = Table(summary_data, colWidths=[2*inch, 2*inch])
    summary_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), colors.lightgrey),
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, -1), 12),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 12),
        ('GRID', (0, 0), (-1, -1), 1, colors.black)
    ]))
    
    story.append(summary_table)
    story.append(Spacer(1, 30))
    
    # Expense details
    if expenses:
        story.append(Paragraph("Expense Details", heading_style))
        
        # Create table data
        data = [['Expense #', 'Employee', 'Title', 'Category', 'Amount', 'Date', 'Status']]
        
        for expense in expenses:
            data.append([
                expense.expense_number,
                expense.employee.full_name,
                expense.title[:30] + ('...' if len(expense.title) > 30 else ''),
                expense.category.name,
                f'KSh {expense.amount:,.2f}',
                expense.expense_date.strftime('%Y-%m-%d'),
                expense.get_status_display()
            ])
        
        # Create table
        table = Table(data, colWidths=[1*inch, 1.5*inch, 2*inch, 1*inch, 1*inch, 0.8*inch, 0.7*inch])
        
        # Style the table
        table.setStyle(TableStyle([
            # Header row
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('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),
            
            # Data rows
            ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 1), (-1, -1), 8),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            
            # Alternate row colors
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ]))
        
        story.append(table)
    
    # Build PDF
    doc.build(story)
    
    # Get PDF content
    buffer.seek(0)
    return buffer

def generate_monthly_expense_summary_pdf(year, month=None):
    """Generate monthly expense summary PDF"""
    from .models import Expense, ExpenseCategory
    from django.db.models import Sum, Count
    
    # Get expenses for the period
    expenses_qs = Expense.objects.filter(
        expense_date__year=year,
        status__in=['approved', 'paid']
    )
    
    if month:
        expenses_qs = expenses_qs.filter(expense_date__month=month)
    
    # Generate category breakdown
    category_breakdown = ExpenseCategory.objects.filter(
        expenses__in=expenses_qs
    ).annotate(
        total_amount=Sum('expenses__amount'),
        expense_count=Count('expenses')
    ).order_by('-total_amount')
    
    buffer = io.BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4)
    story = []
    
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=18,
        spaceAfter=30,
        alignment=1,
    )
    
    # Title
    period_str = f"{year}" if not month else f"{calendar.month_name[month]} {year}"
    story.append(Paragraph(f"Monthly Expense Summary - {period_str}", title_style))
    story.append(Spacer(1, 20))
    
    # Summary table
    total_amount = expenses_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
    total_count = expenses_qs.count()
    
    summary_data = [
        ['Period:', period_str],
        ['Total Expenses:', str(total_count)],
        ['Total Amount:', f'KSh {total_amount:,.2f}'],
    ]
    
    summary_table = Table(summary_data, colWidths=[2*inch, 3*inch])
    summary_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, -1), colors.lightblue),
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, -1), 12),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 12),
        ('GRID', (0, 0), (-1, -1), 1, colors.black)
    ]))
    
    story.append(summary_table)
    story.append(Spacer(1, 30))
    
    # Category breakdown
    if category_breakdown:
        story.append(Paragraph("Breakdown by Category", styles['Heading2']))
        
        cat_data = [['Category', 'Number of Expenses', 'Total Amount', 'Percentage']]
        
        for category in category_breakdown:
            percentage = (category.total_amount / total_amount * 100) if total_amount > 0 else 0
            cat_data.append([
                category.name,
                str(category.expense_count),
                f'KSh {category.total_amount:,.2f}',
                f'{percentage:.1f}%'
            ])
        
        cat_table = Table(cat_data, colWidths=[2*inch, 1.5*inch, 1.5*inch, 1*inch])
        cat_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ]))
        
        story.append(cat_table)
    
    doc.build(story)
    buffer.seek(0)
    return buffer
