"""Shared ReportLab PDF builder for cemetery plot purchase agreements."""
from __future__ import annotations

import base64
from decimal import Decimal
from io import BytesIO
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from src.apps.sales.models.contract import Contract


def build_contract_pdf_bytes(contract: "Contract") -> bytes:
    """Build a signed contract PDF and return the raw bytes."""
    from reportlab.lib import colors
    from reportlab.lib.pagesizes import letter
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch
    from reportlab.lib.utils import ImageReader  # noqa: F401 (kept for potential canvas use)
    from reportlab.platypus import (
        SimpleDocTemplate,
        Paragraph,
        Spacer,
        Table,
        TableStyle,
        HRFlowable,
        Image as RLImage,
    )

    buf = BytesIO()
    doc = SimpleDocTemplate(
        buf,
        pagesize=letter,
        rightMargin=0.75 * inch,
        leftMargin=0.75 * inch,
        topMargin=0.75 * inch,
        bottomMargin=0.75 * inch,
    )

    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        "ContractTitle",
        parent=styles["Title"],
        fontSize=16,
        spaceAfter=4,
        textColor=colors.HexColor("#1a1a2e"),
    )
    heading_style = ParagraphStyle(
        "SectionHeading",
        parent=styles["Heading2"],
        fontSize=11,
        spaceBefore=12,
        spaceAfter=4,
        textColor=colors.HexColor("#2563eb"),
    )
    normal = styles["Normal"]
    small_style = ParagraphStyle(
        "Small",
        parent=normal,
        fontSize=8,
        textColor=colors.HexColor("#6b7280"),
    )

    story = []

    # Letterhead
    story.append(Paragraph("INDELIS Cemetery", title_style))
    story.append(Paragraph("Cemetery Plot Purchase Agreement", styles["Heading1"]))
    story.append(HRFlowable(width="100%", thickness=1, color=colors.HexColor("#2563eb")))
    story.append(Spacer(1, 0.15 * inch))

    # Contract meta
    signed_date = contract.signed_at.strftime("%B %d, %Y") if contract.signed_at else "N/A"
    meta_data = [
        ["Contract Number:", contract.contract_number or "—"],
        ["Contract Type:", (contract.contract_type or "—").replace("_", " ").title()],
        ["Date Signed:", signed_date],
        ["Status:", (contract.status or "—").upper()],
    ]
    meta_table = Table(meta_data, colWidths=[2 * inch, 4 * inch])
    meta_table.setStyle(TableStyle([
        ("FONTNAME", (0, 0), (0, -1), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
        ("TEXTCOLOR", (0, 0), (0, -1), colors.HexColor("#374151")),
    ]))
    story.append(meta_table)
    story.append(Spacer(1, 0.2 * inch))

    # Purchaser details
    story.append(Paragraph("Purchaser Information", heading_style))
    purchaser_data = [
        ["Name:", contract.purchaser_name or "—"],
        ["Email:", contract.purchaser_email or "—"],
        ["Phone:", contract.purchaser_phone or "—"],
        ["Address:", contract.purchaser_address or "—"],
    ]
    purchaser_table = Table(purchaser_data, colWidths=[1.5 * inch, 5 * inch])
    purchaser_table.setStyle(TableStyle([
        ("FONTNAME", (0, 0), (0, -1), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
    ]))
    story.append(purchaser_table)
    story.append(Spacer(1, 0.2 * inch))

    # Line items table
    story.append(Paragraph("Items", heading_style))
    line_items = contract.line_items or []
    li_headers = [["Description", "Qty", "Unit Price", "Subtotal"]]
    li_rows = []
    subtotal = Decimal("0")
    for item in line_items:
        unit = Decimal(str(item.unit_price))
        qty = item.quantity
        total = Decimal(str(item.line_total))
        subtotal += total
        li_rows.append([item.description, str(qty), f"${unit:,.2f}", f"${total:,.2f}"])

    if not li_rows:
        li_rows = [["No line items", "", "", ""]]

    hst_rate = Decimal("0.13")
    hst_amount = (subtotal * hst_rate).quantize(Decimal("0.01"))
    grand_total = subtotal + hst_amount

    summary_rows = [
        ["", "", "Subtotal:", f"${subtotal:,.2f}"],
        ["", "", "HST (13%):", f"${hst_amount:,.2f}"],
        ["", "", "Total:", f"${grand_total:,.2f}"],
    ]

    li_col_widths = [3.5 * inch, 0.5 * inch, 1.25 * inch, 1.25 * inch]
    li_table_data = li_headers + li_rows + summary_rows
    li_table = Table(li_table_data, colWidths=li_col_widths)
    li_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1e3a5f")),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 10),
        ("ALIGN", (1, 0), (-1, 0), "RIGHT"),
        ("FONTSIZE", (0, 1), (-1, -1), 9),
        ("ROWBACKGROUNDS", (0, 1), (-1, len(li_rows)), [colors.white, colors.HexColor("#f9fafb")]),
        ("ALIGN", (1, 1), (-1, -1), "RIGHT"),
        ("FONTNAME", (2, len(li_rows) + 1), (2, -1), "Helvetica-Bold"),
        ("LINEABOVE", (2, len(li_rows) + 1), (-1, len(li_rows) + 1), 1, colors.HexColor("#d1d5db")),
        ("FONTNAME", (2, -1), (-1, -1), "Helvetica-Bold"),
        ("FONTSIZE", (2, -1), (-1, -1), 10),
        ("GRID", (0, 0), (-1, len(li_rows)), 0.5, colors.HexColor("#e5e7eb")),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("RIGHTPADDING", (0, 0), (-1, -1), 6),
    ]))
    story.append(li_table)
    story.append(Spacer(1, 0.15 * inch))

    # Payment plan
    if contract.payment_plan_type:
        story.append(Paragraph(
            f"<b>Payment Plan:</b> {contract.payment_plan_type.replace('_', ' ').title()}",
            normal,
        ))
        story.append(Spacer(1, 0.2 * inch))

    # Signature section
    story.append(Paragraph("Signatures", heading_style))
    story.append(HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#d1d5db")))
    story.append(Spacer(1, 0.1 * inch))

    if contract.purchaser_signature_b64:
        try:
            sig_b64 = contract.purchaser_signature_b64
            if "," in sig_b64:
                sig_b64 = sig_b64.split(",", 1)[1]
            sig_bytes = base64.b64decode(sig_b64)
            sig_img = RLImage(BytesIO(sig_bytes), width=2.5 * inch, height=0.75 * inch)
            story.append(Paragraph("<b>Purchaser Signature:</b>", normal))
            story.append(Spacer(1, 0.05 * inch))
            sig_img_table = Table([[sig_img]], colWidths=[2.5 * inch], rowHeights=[0.75 * inch])
            sig_img_table.setStyle(TableStyle([
                ("ALIGN", (0, 0), (-1, -1), "LEFT"),
                ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor("#d1d5db")),
            ]))
            story.append(sig_img_table)
        except Exception:
            story.append(Paragraph("Purchaser Signature: [on file]", normal))
    else:
        story.append(Paragraph("Purchaser Signature: [on file]", normal))

    story.append(Spacer(1, 0.1 * inch))
    story.append(Paragraph(f"<b>Purchaser Name:</b> {contract.purchaser_name or '—'}", normal))
    story.append(Spacer(1, 0.1 * inch))
    story.append(Paragraph(f"<b>Witness Name:</b> {contract.witness_name or '—'}", normal))
    story.append(Spacer(1, 0.2 * inch))
    story.append(Paragraph(
        "This document constitutes a legally binding agreement between the purchaser "
        "and INDELIS Cemetery upon execution by both parties.",
        small_style,
    ))

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