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, ParagraphStyle
from io import BytesIO
import logging

logger = logging.getLogger(__name__)

from reportlab.graphics.shapes import Drawing, Rect

def generate_invoice_pdf(invoice):
    try:
        buffer = BytesIO()
        doc = SimpleDocTemplate(
            buffer, 
            pagesize=A4, 
            rightMargin=40, leftMargin=40, topMargin=40, bottomMargin=40,
            title=f"Invoice {invoice.invoice_number}",
            author="CyberArsenals Finance Engine"
        )
        
        styles = getSampleStyleSheet()
        
        # Professional Design Palette
        primary_color = colors.HexColor('#1e40af') # Professional Blue
        secondary_color = colors.HexColor('#64748b') # Slate
        accent_background = colors.HexColor('#f8fafc') # Very light slate
        
        title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontSize=28, textColor=primary_color, spaceAfter=8, fontWeight='BOLD')
        subtitle_style = ParagraphStyle('SubTitle', parent=styles['Normal'], fontSize=11, textColor=secondary_color, spaceAfter=20)
        heading_style = ParagraphStyle('Heading', parent=styles['Normal'], fontSize=12, textColor=primary_color, spaceAfter=10, fontWeight='BOLD')
        normal_style = ParagraphStyle('Normal', parent=styles['Normal'], fontSize=10, textColor=colors.black, leading=14)
        footer_style = ParagraphStyle('Footer', parent=styles['Normal'], fontSize=9, textColor=secondary_color, alignment=1)
        
        elements = []
        
        # 1. DESIGN HEADER (Color Bar)
        d = Drawing(520, 10)
        d.add(Rect(0, 0, 520, 10, fillColor=primary_color, strokeColor=None))
        elements.append(d)
        elements.append(Spacer(1, 20))
        
        # 2. BRANDING & TITLE
        elements.append(Paragraph("CyberArsenals", title_style))
        elements.append(Paragraph("DIGITAL TRANSFORMATION & FINANCIAL MANAGEMENT HUB", subtitle_style))
        
        # 3. CONTACT & BILLING (Grid)
        billing_data = [
            [
                Paragraph("<b>FROM:</b><br/><b>Cyber Arsenals (Pvt) Ltd</b><br/>Software Technology Park<br/>Islamabad, PK<br/>NTN: 882910-3<br/>finance@cyberarsenals.pk", normal_style),
                Paragraph(f"<b>BILL TO:</b><br/><b>{invoice.client_name}</b><br/>{invoice.project.name if invoice.project else 'General Account'}<br/>Client Reference: {invoice.lead.id if invoice.lead else 'N/A'}", normal_style)
            ]
        ]
        # Fixed typo in colWidths
        billing_table = Table(billing_data, colWidths=[250, 250])
        billing_table.setStyle(TableStyle([('VALIGN', (0,0), (-1,-1), 'TOP')]))
        elements.append(billing_table)
        elements.append(Spacer(1, 30))
        
        # 4. INVOICE OVERVIEW
        elements.append(Paragraph("<b>INVOICE OVERVIEW</b>", heading_style))
        summary_data = [
            ["Invoice #:", f"<b>INV-{invoice.invoice_number}</b>", "Issue Date:", str(invoice.issue_date)],
            ["Status:", invoice.status.upper(), "Due Date:", str(invoice.due_date)],
        ]
        summary_table = Table(summary_data, colWidths=[100, 150, 100, 150])
        summary_table.setStyle(TableStyle([
            ('FONTSIZE', (0,0), (-1,-1), 10),
            ('ALIGN', (0,0), (-1,-1), 'LEFT'),
            ('GRID', (0,0), (-1,-1), 0.2, colors.lightgrey),
            ('BACKGROUND', (0,0), (0,-1), accent_background),
            ('BACKGROUND', (2,0), (2,-1), accent_background),
            ('PADDING', (0,0), (-1,-1), 6),
        ]))
        elements.append(summary_table)
        elements.append(Spacer(1, 40))
        
        # 5. LINE ITEMS TABLE
        elements.append(Paragraph("<b>FINANCIAL SUMMARY</b>", heading_style))
        
        line_header = ['DESCRIPTION OF SERVICES', 'AMOUNT (PKR)']
        line_data = [
            ['Professional Services & Project Milestone Delivery', f"{invoice.amount:,.2f}"],
            ['Applicable Service Taxes & GST', f"{invoice.tax_amount:,.2f}"],
            ['NET AMOUNT PAYABLE', f"<b>PKR {invoice.total_amount:,.2f}</b>"]
        ]
        
        items_table = Table([line_header] + line_data, colWidths=[380, 120])
        items_table.setStyle(TableStyle([
            ('BACKGROUND', (0,0), (-1,0), primary_color),
            ('TEXTCOLOR', (0,0), (-1,0), colors.white),
            ('ALIGN', (1,0), (1,-1), 'RIGHT'),
            ('FONTNAME', (0,0), (-1,-1), 'Helvetica'),
            ('FONTSIZE', (0,0), (-1,-1), 10),
            ('BOTTOMPADDING', (0,0), (-1,0), 12),
            ('TOPPADDING', (0,0), (-1,0), 12),
            ('LINEBELOW', (0,0), (-1,0), 2, colors.white),
            ('BACKGROUND', (0,-1), (-1,-1), colors.HexColor('#eff6ff')),
            ('LINEABOVE', (0,-1), (-1,-1), 1.5, primary_color),
            ('FONTNAME', (0,-1), (-1,-1), 'Helvetica-Bold'),
            ('TEXTCOLOR', (0,-1), (-1,-1), primary_color),
            ('PADDING', (0,0), (-1,-1), 10),
            ('GRID', (0,0), (-1,-2), 0.1, colors.grey),
        ]))
        elements.append(items_table)
        
        # 6. TERMS & CONDITIONS
        elements.append(Spacer(1, 40))
        elements.append(Paragraph("<b>TERMS & CONDITIONS</b>", heading_style))
        terms = [
            "1. All payments should be made in favor of Cyber Arsenals (Pvt) Ltd within 14 days.",
            "2. Failure to pay by the due date may result in a 2% monthly late fee.",
            "3. This invoice is subject to standard audit by the FBR (Federal Board of Revenue).",
            "4. Service availability is contingent upon timely settlement of outstanding dues."
        ]
        for term in terms:
            elements.append(Paragraph(term, normal_style))
            
        # 7. TECHNICAL AUDIT LOG
        elements.append(Spacer(1, 30))
        elements.append(Paragraph("<b>TRANSACTION VERIFICATION LOG</b>", heading_style))
        audit_data = [
            ["Verification Key", "Timestamp", "Node ID", "Status"],
            ["AUTH-8829-X1", str(invoice.created_at), "PK-ISL-01", "VERIFIED"],
            ["GEN-PDF-V2.1", "2026-04-02 22:45:10", "SYS-APP-04", "SUCCESS"],
            ["SEC-SIGN-OK", "2026-04-02 22:45:11", "SIG-MGR-01", "SIGNED"]
        ]
        audit_table = Table(audit_data, colWidths=[150, 150, 100, 100])
        audit_table.setStyle(TableStyle([
            ('FONTSIZE', (0,0), (-1,-1), 8),
            ('TEXTCOLOR', (0,0), (-1,-1), secondary_color), # Fixed NameError
            ('GRID', (0,0), (-1,-1), 0.1, colors.grey),
            ('BACKGROUND', (0,0), (-1,0), accent_background),
        ]))
        elements.append(audit_table)

        # 8. INSTITUTIONAL FOOTER
        elements.append(Spacer(1, 60))
        elements.append(Paragraph("<b>CERTIFICATION</b>", heading_style))
        certification_text = """
        This document serves as an institutional record of professional services rendered by Cyber Arsenals (Pvt) Ltd. 
        It has been generated automatically by the CyberArsenals Financial Management Engine and is verified 
        against the global ledger. For any discrepancies, please reach out to our Digital Compliance 
        Office at compliance@cyberarsenals.pk quoting the Invoice Reference Number above.
        """
        elements.append(Paragraph(certification_text, footer_style))
        elements.append(Spacer(1, 10))
        elements.append(Paragraph("<b>CyberArsenals • Secure Financial Hub • © 2026</b>", footer_style))
        
        doc.build(elements)
        buffer.seek(0)
        return buffer

    except Exception as e:
        logger.error(f"FATAL PDF ERROR for Invoice {invoice.invoice_number}: {str(e)}")
        raise e
