"""PDF: orden de compra para enviar al proveedor."""
from __future__ import annotations

import io
from decimal import Decimal

from reportlab.lib import colors
from reportlab.lib.units import cm
from reportlab.platypus import Paragraph, Spacer, Table, TableStyle

from ..models import Purchase
from .brand import (
    NES_BLACK,
    NES_GRAY_BG,
    NES_GRAY_LINE,
    NES_GRAY_TEXT,
    NES_YELLOW,
    build_branded_pdf,
    data_table_style,
    info_card_style,
    styles,
)


def _money(amount, currency="USD") -> str:
    if amount is None:
        return "—"
    return f"$ {Decimal(amount):,.2f}"


def _dt(value) -> str:
    """Formatea un datetime tolerando None. Las fechas '0000-00-00' cargadas por
    SQL llegan como None vía PyMySQL; sin esto el PDF rompía con AttributeError."""
    return value.strftime("%Y-%m-%d %H:%M") if value else "—"


_STATUS_LABEL = {
    "draft": ("Borrador", "#fdebd0", "#b9770e"),
    "received": ("Recibida", "#d4efdf", "#1d8348"),
    "cancelled": ("Cancelada", "#e8e8ec", "#6b6b76"),
}


def _status_badge(status_value: str):
    label, bg, fg = _STATUS_LABEL.get(status_value, (status_value, "#e8e8ec", "#6b6b76"))
    s = styles()
    p = Paragraph(f"<b>{label.upper()}</b>", s["small"])
    badge = Table([[p]], colWidths=[None])
    badge.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor(bg)),
        ("TEXTCOLOR", (0, 0), (-1, -1), colors.HexColor(fg)),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("RIGHTPADDING", (0, 0), (-1, -1), 6),
        ("TOPPADDING", (0, 0), (-1, -1), 2),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 2),
        ("BOX", (0, 0), (-1, -1), 0.4, colors.HexColor(fg)),
    ]))
    return badge


def build_purchase_order_pdf(purchase: Purchase) -> io.BytesIO:
    s = styles()
    elements: list = []

    status = purchase.status.value if hasattr(purchase.status, "value") else str(purchase.status)

    # Banda meta
    meta_row = Table(
        [[
            Paragraph(f"<b>Emitida</b><br/>{_dt(purchase.created_at)}", s["small"]),
            Paragraph(f"<b>Recibida</b><br/>{_dt(purchase.received_at)}", s["small"]),
            Paragraph(f"<b>Sede destino</b><br/>" + (purchase.store.name if purchase.store else "Sin asignar"), s["small"]),
            _status_badge(status),
        ]],
        colWidths=[3.6 * cm, 3.6 * cm, 5.4 * cm, 5.4 * cm],
    )
    meta_row.setStyle(TableStyle([
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("LEFTPADDING", (0, 0), (-1, -1), 0),
        ("RIGHTPADDING", (0, 0), (-1, -1), 0),
    ]))
    elements.append(meta_row)
    elements.append(Spacer(1, 12))

    # Proveedor + receptor
    sup = purchase.supplier
    sup_lines = ['<font name="Helvetica-Bold" color="#0E0E14">PROVEEDOR</font>']
    if sup:
        sup_lines.append(f'<font name="Helvetica-Bold">{sup.name}</font>')
        if sup.document: sup_lines.append(f"Doc: {sup.document}")
        if sup.contact_name: sup_lines.append(f"Contacto: {sup.contact_name}")
        if sup.phone: sup_lines.append(f"Tel: {sup.phone}")
        if sup.email: sup_lines.append(sup.email)
        if sup.address: sup_lines.append(sup.address)

    receptor_lines = ['<font name="Helvetica-Bold" color="#0E0E14">DESTINATARIO</font>',
                      '<font name="Helvetica-Bold">ChevroCaracas</font>']
    if purchase.store:
        receptor_lines.append(f"Sede: {purchase.store.code} · {purchase.store.name}")
    receptor_lines.append(f"Pedido por: {purchase.user.full_name if purchase.user else '—'}")

    info_table = Table(
        [[
            Paragraph("<br/>".join(sup_lines), s["normal"]),
            Paragraph("<br/>".join(receptor_lines), s["normal"]),
        ]],
        colWidths=[10.5 * cm, 7.5 * cm],
    )
    info_table.setStyle(info_card_style())
    elements.append(info_table)
    elements.append(Spacer(1, 14))

    # Items
    elements.append(Paragraph("Detalle de la orden", s["h2"]))
    items_data = [["#", "Producto", "SKU", "Cant", "Costo unit.", "Total"]]
    for idx, it in enumerate(purchase.items, start=1):
        items_data.append([
            str(idx),
            Paragraph(it.product.name if it.product else "—", s["normal"]),
            Paragraph(f"<font name='Courier'>{it.product.sku if it.product else '—'}</font>", s["small"]),
            str(it.quantity),
            _money(it.unit_cost, purchase.currency),
            _money(it.line_total, purchase.currency),
        ])
    items_table = Table(
        items_data,
        colWidths=[0.8 * cm, 7.6 * cm, 3.4 * cm, 1.2 * cm, 2.5 * cm, 2.5 * cm],
        repeatRows=1,
    )
    style = data_table_style()
    style.add("ALIGN", (0, 1), (0, -1), "CENTER")
    style.add("ALIGN", (3, 1), (-1, -1), "RIGHT")
    items_table.setStyle(style)
    elements.append(items_table)
    elements.append(Spacer(1, 10))

    # Totales (con TOTAL en banda amarilla)
    totals_rows = [
        ["", "Subtotal", _money(purchase.subtotal, purchase.currency)],
    ]
    if purchase.discount and Decimal(purchase.discount) > 0:
        totals_rows.append(["", "Descuento", f"− {_money(purchase.discount, purchase.currency)}"])
    totals_rows.append(["", f"TOTAL · {purchase.currency}", _money(purchase.total, purchase.currency)])

    totals_table = Table(totals_rows, colWidths=[8.5 * cm, 5.0 * cm, 4.5 * cm])
    totals_style = TableStyle([
        ("ALIGN", (1, 0), (-1, -1), "RIGHT"),
        ("FONTNAME", (1, 0), (-1, -2), "Helvetica"),
        ("FONTSIZE", (1, 0), (-1, -2), 9),
        ("TEXTCOLOR", (1, 0), (-1, -2), NES_GRAY_TEXT),
        ("LINEABOVE", (1, -1), (-1, -1), 1.5, NES_BLACK),
        ("FONTNAME", (1, -1), (-1, -1), "Helvetica-Bold"),
        ("FONTSIZE", (1, -1), (-1, -1), 12),
        ("TEXTCOLOR", (1, -1), (-1, -1), NES_BLACK),
        ("BACKGROUND", (1, -1), (-1, -1), NES_YELLOW),
        ("TOPPADDING", (1, -1), (-1, -1), 8),
        ("BOTTOMPADDING", (1, -1), (-1, -1), 8),
        ("LEFTPADDING", (1, -1), (-1, -1), 10),
        ("RIGHTPADDING", (1, -1), (-1, -1), 10),
    ])
    totals_table.setStyle(totals_style)
    elements.append(totals_table)
    elements.append(Spacer(1, 14))

    # AP info (si existe)
    ap = getattr(purchase, "payable", None)
    if ap:
        ap_status = ap.status.value if hasattr(ap.status, "value") else str(ap.status)
        elements.append(Paragraph("Cuenta por pagar", s["h2"]))
        ap_table = Table(
            [[
                Paragraph(f"<b>Total</b><br/>{_money(ap.total, ap.currency)}", s["small"]),
                Paragraph(f"<b>Pagado</b><br/>{_money(ap.paid, ap.currency)}", s["small"]),
                Paragraph(f"<b>Saldo</b><br/>{_money(ap.balance, ap.currency)}", s["small"]),
                Paragraph(f"<b>Vencimiento</b><br/>{ap.due_date.isoformat() if ap.due_date else '—'}", s["small"]),
                _status_badge(ap_status),
            ]],
            colWidths=[3.6 * cm, 3.6 * cm, 3.6 * cm, 3.6 * cm, 3.6 * cm],
        )
        ap_table.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, -1), NES_GRAY_BG),
            ("BOX", (0, 0), (-1, -1), 0.5, NES_GRAY_LINE),
            ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
            ("LEFTPADDING", (0, 0), (-1, -1), 8),
            ("RIGHTPADDING", (0, 0), (-1, -1), 8),
            ("TOPPADDING", (0, 0), (-1, -1), 6),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ]))
        elements.append(ap_table)
        elements.append(Spacer(1, 10))

    # Notas
    if purchase.notes:
        elements.append(Paragraph("Notas", s["h2"]))
        elements.append(Paragraph(purchase.notes.replace("\n", "<br/>"), s["normal"]))
        elements.append(Spacer(1, 10))

    elements.append(Spacer(1, 14))
    elements.append(Paragraph(
        "<i>Orden de compra emitida por <b>ChevroCaracas</b>. Confirmar despacho contra esta referencia.</i>",
        s["footer"],
    ))

    return build_branded_pdf(
        elements,
        title="Orden de compra",
        subtitle=purchase.number,
    )
