from reportlab.platypus import Paragraph, Spacer, Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.units import mm
from reportlab.lib.utils import ImageReader
from pathlib import Path

from reportlab.platypus import Paragraph, Table, TableStyle, Spacer, KeepInFrame
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_RIGHT
from reportlab.lib.units import mm

def partner(elements, styles, data):

    company = data.partner

    # Style aligné à droite
    header_style = ParagraphStyle(
        name="HeaderRight",
        parent=styles["Normal"],
        alignment=0,
        fontSize=9,
        spaceAfter=0,
    )

    lines = [
        company.name,
        f"{company.address.adr_l1} {company.address.adr_l2} {company.address.adr_l3}",
        f"{company.address.postcode} {company.address.city} - {company.address.country_id}",
        f"SIREN : {company.siren}"
    ]

    paragraphs = [Paragraph(line, header_style) for line in lines]

    table = Table(
        [[p] for p in paragraphs],   # 1 colonne, plusieurs lignes
        colWidths=[70*mm],
        hAlign="RIGHT"
    )

    table.setStyle(TableStyle([
        ("VALIGN", (0,0), (-1,-1), "TOP"),
        ("LEFTPADDING", (0,0), (-1,-1), 0),
        ("RIGHTPADDING", (0,0), (-1,-1), 0),
        ("TOPPADDING", (0,0), (-1,-1), 0),
        ("BOTTOMPADDING", (0,0), (-1,-1), 2),
    ]))

    elements.append(table)

def four_columns_block(elements, styles, data,col_widths=None):

    invoice = data.invoice
    elements.append(Spacer(1, 30))
    pr = Paragraph(
        f"<b>Facture : {invoice.name}</b>",
        styles["TempTitle"]
    )

    elements.append(pr)
    elements.append(Spacer(1, 20))

    columns = [
        ("Date de la facture :", invoice.date),
        ("Date d'échéance", invoice.expiration),
        ("Source", invoice.order),
        ("Référence", invoice.reference),
    ]


    cells = []
    for title, content in columns:
        cells.append(
            Paragraph(
                f"<b>{title}</b><br/>{content}",
                styles["Normal"]
            )
        )

    table = Table(
        [cells],   # ← UNE seule ligne
        colWidths=col_widths,
        hAlign="LEFT"
    )

    table.setStyle(TableStyle([
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("LEFTPADDING", (0,0), (-1,-1), 6),
        ("RIGHTPADDING", (0,0), (-1,-1), 6),
        ("TOPPADDING", (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
    ]))

    elements.append(table)

def items_table(elements, styles, data):
    rows = [["Description", "Quantity", "Unit Price", "TVA","Amount"]]
    total = 0

    max_width = 2400*mm
    max_height = 10000  # hauteur max de la cellule

    for item in data.invoice_lines:
        product_description = KeepInFrame(max_width, max_height, [Paragraph(item.product_description, styles['Normal'])],mode='shrink')
        quantity = KeepInFrame(max_width, max_height, [Paragraph(f"{item.quantity}", styles['Normal'])],mode='shrink')
        unit_price = KeepInFrame(max_width, max_height, [Paragraph(f"{item.unit_price:.2f}", styles['Normal'])],mode='shrink')
        tva_code = KeepInFrame(max_width, max_height, [Paragraph(f"{item.tva_code} %", styles['Normal'])],mode='shrink')
        amount = KeepInFrame(max_width, max_height, [Paragraph(f"{item.quantity * item.unit_price:.2f} €", styles['Normal'])],mode='shrink')

        rows.append([
            product_description,
            quantity,
            unit_price,
            tva_code,
            amount,
        ])

    table = Table(
        rows,
        colWidths=[90*mm, 25*mm, 25*mm, 25*mm, 25*mm],
        rowHeights=15*mm,
        repeatRows=1,
        vAlign='Top',
        hAlign="CENTER"
    )

    style_commands = [
        # Header
        ("LINEBELOW", (0,0), (-1,0), 1, colors.black),
        ("ALIGN", (1, 1), (-1, -1), "RIGHT"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTSIZE", (0, 0), (-1, -1), 11),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
    ]

    # Alternance de couleurs (lignes de données uniquement)
    for row_index in range(1, len(rows)):
        if row_index % 2 == 1:
            style_commands.append(
                ("BACKGROUND", (0, row_index), (-1, row_index), colors.whitesmoke)
            )


    table.setStyle(TableStyle(style_commands))

    elements.append(table)
    elements.append(Spacer(1, 15))


def summary_tables(elements,data):

    invoice_lines = data.get("invoice_lines", [])
    invoice_sum = data.get("invoice_header", [])

    total_ht = 0
    total_tva = 0

    # Ligne vide d'espacement en haut
    rows = [["", ""]]

    # Calcul du total HT
    for line in invoice_lines:
        total_ht += line.get("unit_price", 0) * line.get("quantity")

    rows.append(["Montant hors taxes", f"{total_ht:.2f} €"])

    # Ajout dynamique des lignes TVA
    for line in invoice_sum:
        tva_label = line.get("tva_texte", "")
        tva_amount = line.get("amount", 0)

        rows.append([tva_label, f"{tva_amount:.2f} €"])
        total_tva += tva_amount

    # Total TTC
    total_ttc = total_ht + total_tva
    rows.append(["Total", f"{total_ttc:.2f} €"])

    # Création du tableau
    table = Table(
        rows,
        colWidths=[90 * mm, 25 * mm],
        rowHeights=15 * mm,
        vAlign='Top',
        hAlign="RIGHT"
    )

    style_commands = [
        ("ALIGN", (1, 1), (-1, -1), "RIGHT"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTNAME", (0, len(rows)-1), (-1, len(rows)-1), "Helvetica-Bold"),  # Total en gras
    ]

    # Alternance de couleurs (lignes de données uniquement)
    for row_index in range(1, len(rows)):
        if row_index % 2 == 1:
            style_commands.append(
                ("BACKGROUND", (0, row_index), (-1, row_index), colors.whitesmoke)
            )

    table.setStyle(TableStyle(style_commands))

    elements.append(table)
    elements.append(Spacer(1, 15))


def invoice_description(elements, styles, data):
    for line in data.invoice.description:
        elements.append(Paragraph(line, styles["Normal"]))
        elements.append(Spacer(1, 4))

def draw_footer(canvas, doc, footer):
    canvas.saveState()
    canvas.setFont("Helvetica", 10)

    # --- Position verticale de départ ---
    y_start = 20 * mm

    # --- Trait de séparation ---
    canvas.setLineWidth(0.5)
    canvas.line(doc.leftMargin, y_start + 10, doc.pagesize[0] - doc.rightMargin, y_start + 10)

    # --- Texte centré ---
    line = f"{footer.left} | {footer.middle} | {footer.bottom}"


    # drawCentredString centre horizontalement sur la page
    canvas.drawCentredString(doc.pagesize[0]/2, y_start, line)
    y_start -= 15  # espace entre les lignes (10 points)
    canvas.drawCentredString(doc.pagesize[0]/2, y_start, footer.bottom)
    y_start -= 15
    # --- Numéro de page (droite) ---
    canvas.drawCentredString(
        doc.pagesize[0]/2,
        y_start,
        f"Page {doc.page}"
    )

    canvas.restoreState()

def draw_header(canvas, doc, company, logopath):
    canvas.saveState()

    HEADER_Y = doc.pagesize[1] - 20 * mm
    DELTA_IMAGE = 50
    logo = ImageReader(str(Path(logopath)))
    canvas.drawImage(
        logo,
        doc.leftMargin,
        HEADER_Y - 25*mm,
        width=38*mm,
        height=38*mm,
        preserveAspectRatio=True,
        mask="auto"
    )

    y=HEADER_Y
    # --- COMPANY NAME ---
    canvas.setFont("Helvetica", 9)
    canvas.drawString(
        doc.leftMargin + DELTA_IMAGE + 35 * mm,
        y,
        company.name
    )

    y -= 14
    canvas.drawString(
        doc.leftMargin + DELTA_IMAGE + 35 * mm,
        y,
        f"{company.address.adr_l1} {company.address.adr_l2} {company.address.adr_l3}"
    )

    y -= 14
    canvas.drawString(
        doc.leftMargin + DELTA_IMAGE + 35 * mm,
        y,
        f"{company.address.postcode} {company.address.city} - {company.address.country_id}"
    )
    y -= 14
    canvas.drawString(
        doc.leftMargin + DELTA_IMAGE + 35 * mm,
        y,
        f"SIREN : {company.siren}"
    )

    canvas.restoreState()
