#!/usr/bin/env python3
import sys
import json
from datetime import datetime
from reportlab.lib.pagesizes import letter
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_LEFT, TA_RIGHT, TA_CENTER

def generate_quote(data, output_path):
    doc = SimpleDocTemplate(output_path, pagesize=letter, topMargin=0.5*inch, bottomMargin=0.5*inch)
    story = []
    styles = getSampleStyleSheet()

    # Company header
    header_style = ParagraphStyle(
        'CustomHeader',
        parent=styles['Heading1'],
        fontSize=18,
        textColor=colors.HexColor('#1e293b'),
        spaceAfter=6,
        alignment=TA_LEFT,
        fontName='Helvetica-Bold'
    )
    story.append(Paragraph("FOYER SIDE (PTY) LTD", header_style))

    # Date and reference
    date_ref_style = ParagraphStyle('DateRef', parent=styles['Normal'], fontSize=10)
    year = datetime.now().strftime('%y')
    ref_text = f"Date: {data['date']} &nbsp;&nbsp;&nbsp;&nbsp; {'Quote' if data['type']=='quote' else 'Invoice'}Ref: {year}-{data['domain_clean']}"
    story.append(Paragraph(ref_text, date_ref_style))
    story.append(Spacer(1, 10))

    # Invoice For
    invoice_type = "Quote" if data['type']=='quote' else "Invoice"
    title_style = ParagraphStyle('InvoiceFor', parent=styles['Normal'], fontSize=11, fontName='Helvetica-Bold')
    story.append(Paragraph(f"{invoice_type} For<br/>{data['description']}", title_style))
    story.append(Spacer(1, 10))

    # From/To table
    from_to_data = [
        ['From', '', 'To'],
        [
            f"Foyer Side (PTY) Ltd\n76981470\ninfo@foyerside.co.bw",
            '',
            data['client_name']
        ]
    ]
    from_to_table = Table(from_to_data, colWidths=[2.2*inch, 0.5*inch, 2.2*inch])
    from_to_table.setStyle(TableStyle([
        ('FONT', (0, 0), (-1, -1), 'Helvetica', 10),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('TOPPADDING', (0, 0), (-1, -1), 6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
    ]))
    story.append(from_to_table)
    story.append(Spacer(1, 15))

    # Items table
    items_data = [['Invoiced Items', 'Rate', 'Qty', 'Total']]
    for item in data['items']:
        items_data.append([
            item['description'],
            item['rate'],
            item['qty'],
            item['total']
        ])

    items_table = Table(items_data, colWidths=[3.2*inch, 1.2*inch, 0.8*inch, 1.2*inch])
    items_table.setStyle(TableStyle([
        ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10),
        ('FONT', (0, 1), (-1, -1), 'Helvetica', 10),
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#f0f0f0')),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
        ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
        ('ALIGN', (0, 0), (0, -1), 'LEFT'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('TOPPADDING', (0, 0), (-1, -1), 8),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
    ]))
    story.append(items_table)
    story.append(Spacer(1, 15))

    # Totals
    totals_data = [
        ['', '', 'Net Total:', data['net_total']],
        ['', '', 'Grand Total', data['grand_total']]
    ]
    totals_table = Table(totals_data, colWidths=[3.2*inch, 1.2*inch, 0.8*inch, 1.2*inch])
    totals_table.setStyle(TableStyle([
        ('FONT', (0, 0), (-1, -1), 'Helvetica', 10),
        ('FONT', (2, 1), (2, 1), 'Helvetica-Bold', 11),
        ('FONT', (3, 1), (3, 1), 'Helvetica-Bold', 11),
        ('ALIGN', (2, 0), (3, -1), 'RIGHT'),
        ('TOPPADDING', (0, 0), (-1, -1), 6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
    ]))
    story.append(totals_table)
    story.append(Spacer(1, 20))

    # Bank details
    bank_style = ParagraphStyle('Bank', parent=styles['Normal'], fontSize=9)
    story.append(Paragraph("Bank Name: FNB", bank_style))
    story.append(Paragraph("Account Name: FOYER SIDE (PTY) LTD", bank_style))
    story.append(Paragraph("Account Number: 62737435976", bank_style))
    story.append(Paragraph("Branch No: 281667", bank_style))
    story.append(Spacer(1, 10))
    story.append(Paragraph("info@foyerside.co.bw", bank_style))

    doc.build(story)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python3 generate_pdf.py <json_data> <output_path>")
        sys.exit(1)

    data = json.loads(sys.argv[1])
    output_path = sys.argv[2]
    generate_quote(data, output_path)
    print(output_path)
