"""
Real downloadable invoice PDFs for successful Payments (subscription
upgrades and campaign activations) — Billing's payment history previously
only ever showed a list of past payments, no actual invoice document. One
function, `generate_invoice_pdf`, used by the single owner-facing endpoint
in views_owner.py.
"""
from io import BytesIO

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_RIGHT

BRAND_NAVY = colors.HexColor("#021741")
BRAND_BLUE = colors.HexColor("#0C46F7")
BRAND_SLATE = colors.HexColor("#5F6D87")
BRAND_BORDER = colors.HexColor("#DDE4F0")


def _invoice_number(payment):
    return f"DISC-{payment.id:06d}"


def _line_item_description(payment):
    if payment.purpose == "campaign" and payment.campaign_id:
        return f'Campaign promotion — "{payment.campaign.content_title}"'
    if payment.plan_id:
        return f"{payment.plan.name} plan subscription (30 days)"
    return "Discovr charge"


def generate_invoice_pdf(payment):
    """Returns PDF bytes for one successful Payment. Caller is responsible for checking payment.status == 'successful' first."""
    buf = BytesIO()
    doc = SimpleDocTemplate(
        buf, pagesize=A4,
        leftMargin=22 * mm, rightMargin=22 * mm, topMargin=20 * mm, bottomMargin=20 * mm,
    )
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle("BrandTitle", parent=styles["Title"], textColor=BRAND_NAVY, fontSize=22, spaceAfter=2))
    styles.add(ParagraphStyle("Muted", parent=styles["Normal"], textColor=BRAND_SLATE, fontSize=9))
    styles.add(ParagraphStyle("RightMuted", parent=styles["Muted"], alignment=TA_RIGHT))
    styles.add(ParagraphStyle("SectionLabel", parent=styles["Normal"], textColor=BRAND_SLATE, fontSize=8, spaceAfter=2))
    styles.add(ParagraphStyle("BodyNavy", parent=styles["Normal"], textColor=BRAND_NAVY, fontSize=10.5))

    business = payment.business
    owner = business.owner

    elements = [
        Paragraph("Discovr", styles["BrandTitle"]),
        Paragraph("Your Local Business Marketplace", styles["Muted"]),
        Spacer(1, 14 * mm),
    ]

    header_table = Table(
        [[
            [
                Paragraph("BILLED TO", styles["SectionLabel"]),
                Paragraph(business.title, styles["BodyNavy"]),
                Paragraph(owner.get_full_name() or owner.email, styles["Muted"]),
                Paragraph(owner.email, styles["Muted"]),
            ],
            [
                Paragraph(f"INVOICE {_invoice_number(payment)}", ParagraphStyle("InvNo", parent=styles["Normal"], textColor=BRAND_BLUE, fontSize=11, fontName="Helvetica-Bold", alignment=TA_RIGHT)),
                Paragraph(f"Issued {payment.verified_at.strftime('%d %b %Y') if payment.verified_at else payment.created_at.strftime('%d %b %Y')}", styles["RightMuted"]),
                Paragraph(f"Reference {payment.tx_ref}", styles["RightMuted"]),
            ],
        ]],
        colWidths=[95 * mm, 75 * mm],
    )
    header_table.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]))
    elements.append(header_table)
    elements.append(Spacer(1, 12 * mm))

    items_table = Table(
        [
            ["Description", "Amount"],
            [_line_item_description(payment), f"{payment.currency} {payment.amount:,.2f}"],
            ["", ""],
            ["Total paid", f"{payment.currency} {payment.amount:,.2f}"],
        ],
        colWidths=[130 * mm, 40 * mm],
    )
    items_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), BRAND_NAVY),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 9.5),
        ("ALIGN", (1, 0), (1, -1), "RIGHT"),
        ("TOPPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("LINEBELOW", (0, 1), (-1, 1), 0.75, BRAND_BORDER),
        ("FONTNAME", (0, 3), (-1, 3), "Helvetica-Bold"),
        ("FONTSIZE", (0, 3), (-1, 3), 11),
        ("TEXTCOLOR", (0, 3), (-1, 3), BRAND_NAVY),
        ("LINEABOVE", (0, 3), (-1, 3), 1, BRAND_NAVY),
    ]))
    elements.append(items_table)
    elements.append(Spacer(1, 14 * mm))

    elements.append(Paragraph(
        "Payment status: <b>Successful</b> — processed securely through Flutterwave.",
        ParagraphStyle("Status", parent=styles["Normal"], textColor=colors.HexColor("#0C7A50"), fontSize=9.5),
    ))
    elements.append(Spacer(1, 30 * mm))
    elements.append(Paragraph(
        "This invoice was generated automatically by Discovr. If you have questions about this charge, "
        "contact our support team from Discovr for Business &gt; Settings.",
        styles["Muted"],
    ))

    doc.build(elements)
    return buf.getvalue()
