"""PDF de nota de entrega de venta."""
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 KeepTogether, Paragraph, Spacer, Table, TableStyle

from ..models import Sale
from .brand import (
    NES_BLACK,
    NES_GRAY_BG,
    NES_GRAY_LINE,
    NES_GRAY_MUTE,
    NES_GRAY_TEXT,
    NES_YELLOW,
    build_branded_pdf,
    data_table_style,
    info_card_style,
    styles,
)


# Simbolo amigable para el cliente: evita mostrar "VES", usa "Bs".
_SYMBOL = {"USD": "$", "VES": "Bs"}


def _money(amount, currency="USD") -> str:
    if amount is None:
        return "-"
    sym = _SYMBOL.get(currency, currency)
    return f"{sym} {Decimal(str(amount)):,.2f}"


def _display_ctx(sale):
    """Contexto de moneda para la nota de entrega.

    Si el pago es en una moneda secundaria (Bs) con snapshot, TODO el documento
    se muestra en esa moneda con el ajuste del metodo ya plegado en los precios
    (igual que el email al cliente). En ese caso NO aparece ninguna referencia
    al monto en $ ni la conversion. Si no, se muestra en la moneda base (USD).

    Devuelve (native, code, line_mult, disp_total, rate):
      - line_mult: factor para plegar cada linea/subtotal -> moneda mostrada.
      - rate: tasa pura para convertir pagos/saldos ya en USD -> moneda mostrada.
    """
    payment_currency = getattr(sale, "payment_currency", None)
    payment_total = getattr(sale, "payment_total", None)
    subtotal = Decimal(str(sale.subtotal or 0))
    native = bool(payment_currency and payment_currency != sale.currency and payment_total)
    if native:
        disp_total = Decimal(str(payment_total))
        line_mult = (disp_total / subtotal) if subtotal else Decimal("1")
        rate = Decimal(str(getattr(sale, "payment_exchange_rate", None) or 0))
        if rate == 0 and sale.total:
            rate = disp_total / Decimal(str(sale.total))
        return True, payment_currency, line_mult, disp_total, rate
    return False, sale.currency, Decimal("1"), Decimal(str(sale.total or 0)), Decimal("1")


def _status_badge(label: str, hex_bg: str, hex_fg: str = "#0E0E14") -> Table:
    """Mini badge para mostrar estados (status, payment, fulfillment)."""
    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(hex_bg)),
        ("TEXTCOLOR", (0, 0), (-1, -1), colors.HexColor(hex_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(hex_fg)),
    ]))
    return badge


_STATUS_COLOR = {
    "pending": ("#fdebd0", "#b9770e"),
    "confirmed": ("#d4efdf", "#1d8348"),
    "cancelled": ("#e8e8ec", "#6b6b76"),
}
_PAYMENT_COLOR = {
    "pending": ("#fdebd0", "#b9770e"),
    "partial": ("#d6eaf8", "#1f618d"),
    "paid": ("#d4efdf", "#1d8348"),
}
_FULFILL_COLOR = {
    "pending": ("#fdebd0", "#b9770e"),
    "in_progress": ("#d6eaf8", "#1f618d"),
    "completed": ("#d4efdf", "#1d8348"),
}


def build_invoice_pdf(sale: Sale) -> io.BytesIO:
    s = styles()
    elements: list = []

    # Moneda de presentacion (Bs si el pago es en moneda secundaria).
    native, disp_code, line_mult, disp_total, disp_rate = _display_ctx(sale)

    # === Banda meta (estado, fecha, canal) ===
    status = sale.status.value if hasattr(sale.status, "value") else str(sale.status)
    pay_status = sale.payment_status.value if hasattr(sale.payment_status, "value") else str(sale.payment_status)
    full_status = (sale.fulfillment_status.value if hasattr(sale.fulfillment_status, "value")
                   else str(sale.fulfillment_status or "pending"))
    channel = sale.channel.value.upper() if hasattr(sale.channel, "value") else str(sale.channel).upper()

    st_bg, st_fg = _STATUS_COLOR.get(status, ("#e8e8ec", "#6b6b76"))
    py_bg, py_fg = _PAYMENT_COLOR.get(pay_status, ("#e8e8ec", "#6b6b76"))
    fu_bg, fu_fg = _FULFILL_COLOR.get(full_status, ("#e8e8ec", "#6b6b76"))

    meta_row = Table(
        [[
            Paragraph(f"<b>Emitida</b><br/>{sale.created_at.strftime('%Y-%m-%d %H:%M')}", s["small"]),
            Paragraph(f"<b>Canal</b><br/>{channel}", s["small"]),
            _status_badge(f"Venta · {status}", st_bg, st_fg),
            _status_badge(f"Pago · {pay_status}", py_bg, py_fg),
            _status_badge(f"Entrega · {full_status}", fu_bg, fu_fg),
        ]],
        colWidths=[3.6 * cm, 2.4 * cm, 4.0 * cm, 4.0 * cm, 4.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))

    # === Cliente + atendido por ===
    cust = sale.customer
    cust_lines = ['<font name="Helvetica-Bold" color="#0E0E14">CLIENTE</font>']
    if cust:
        cust_lines.append(f'<font name="Helvetica-Bold">{cust.name}</font>')
        if cust.document:
            cust_lines.append(f"Doc: {cust.document}")
        if cust.phone:
            cust_lines.append(f"Tel: {cust.phone}")
        if cust.email:
            cust_lines.append(cust.email)
        if cust.address:
            cust_lines.append(cust.address)
        if cust.city or cust.state:
            cust_lines.append(f"{cust.city or ''}{', ' + cust.state if cust.state else ''}")

    seller_name = sale.user.full_name if sale.user else "Web · Auto-checkout"
    pm = sale.payment_method
    pm_block = ['<font name="Helvetica-Bold" color="#0E0E14">PAGO</font>']
    if pm:
        # En documento en Bs el ajuste queda plegado en los precios y es
        # invisible para el cliente: no se muestra el % ni el codigo de moneda.
        adj_label = ""
        if not native:
            adj = Decimal(pm.adjustment_percent or 0)
            if adj > 0:
                adj_label = f' <font color="#b9770e">(+{adj}%)</font>'
            elif adj < 0:
                adj_label = f' <font color="#1d8348">({adj}% off)</font>'
        pm_block.append(f"Método: {pm.name}{adj_label}")
        if pm.currency and not native:
            pm_block.append(f"Moneda: {pm.currency.code}")
    else:
        pm_block.append("Método: —")
    pm_block.append(f"Atendido por: {seller_name}")

    info_table = Table(
        [[
            Paragraph("<br/>".join(cust_lines), s["normal"]),
            Paragraph("<br/>".join(pm_block), s["normal"]),
        ]],
        colWidths=[10.5 * cm, 7.5 * cm],
    )
    info_table.setStyle(info_card_style())
    elements.append(info_table)
    elements.append(Spacer(1, 14))

    # === Tabla de items ===
    elements.append(Paragraph("Detalle del pedido", s["h2"]))
    items_data = [["#", "Producto", "Serial", "Cant", "Precio", "Total"]]
    for idx, it in enumerate(sale.items, start=1):
        qty = int(it.quantity or 1)
        line_disp = Decimal(str(it.line_total or 0)) * line_mult
        unit_disp = (line_disp / qty) if qty else line_disp
        items_data.append([
            str(idx),
            Paragraph(it.product.name if it.product else "—", s["normal"]),
            Paragraph(f"<font name='Courier'>{it.product_item.serial}</font>"
                      if it.product_item and it.product_item.serial else "—", s["small"]),
            str(it.quantity),
            _money(unit_disp, disp_code),
            _money(line_disp, disp_code),
        ])

    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 ===
    if native:
        # Documento en Bs: solo el total final en Bs, sin desglose de
        # subtotal/descuento/recargo ni referencia al monto en $.
        totals_rows = [["", "TOTAL", _money(disp_total, disp_code)]]
    else:
        totals_rows = [["", "Subtotal", _money(sale.subtotal, disp_code)]]
        if sale.discount and Decimal(sale.discount) > 0:
            totals_rows.append(["", "Descuento", f"− {_money(sale.discount, disp_code)}"])
        if getattr(sale, "surcharge", None) and Decimal(sale.surcharge) > 0:
            totals_rows.append(["", "Recargo", f"+ {_money(sale.surcharge, disp_code)}"])
        totals_rows.append(["", "TOTAL", _money(sale.total, disp_code)])

    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))

    # === Pagos registrados ===
    ar = getattr(sale, "receivable", None)
    if ar and getattr(ar, "payments", None):
        elements.append(Paragraph("Pagos registrados", s["h2"]))
        pay_data = [["Fecha", "Método", "Referencia", "Monto"]]
        for p in ar.payments:
            if native:
                amount_disp = _money(Decimal(str(p.amount or 0)) * disp_rate, disp_code)
            else:
                amount_disp = _money(p.amount, p.currency or sale.currency)
            pay_data.append([
                p.paid_at.strftime("%Y-%m-%d") if p.paid_at else "—",
                (p.payment_method.name if p.payment_method else (p.method or "—")),
                Paragraph(f"<font name='Courier'>{p.reference or '—'}</font>", s["small"]),
                amount_disp,
            ])
        pay_table = Table(pay_data, colWidths=[3 * cm, 5 * cm, 5 * cm, 5 * cm])
        pay_style = data_table_style()
        pay_style.add("ALIGN", (3, 1), (3, -1), "RIGHT")
        pay_table.setStyle(pay_style)
        elements.append(pay_table)
        elements.append(Spacer(1, 8))

        if ar.balance and Decimal(ar.balance) > 0:
            balance_disp = (Decimal(str(ar.balance)) * disp_rate) if native else ar.balance
            balance_box = Table(
                [[Paragraph(
                    f"<b>SALDO PENDIENTE</b>: { _money(balance_disp, disp_code) }",
                    s["callout"],
                )]],
                colWidths=[18 * cm],
            )
            balance_box.setStyle(TableStyle([
                ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#fce4e4")),
                ("BOX", (0, 0), (-1, -1), 1, colors.HexColor("#dc2626")),
                ("TEXTCOLOR", (0, 0), (-1, -1), colors.HexColor("#dc2626")),
                ("LEFTPADDING", (0, 0), (-1, -1), 12),
                ("TOPPADDING", (0, 0), (-1, -1), 6),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
            ]))
            elements.append(balance_box)
            elements.append(Spacer(1, 8))

    # === Instrucciones de pago (si el metodo las tiene) ===
    if pm and pm.instructions:
        elements.append(Paragraph("Instrucciones de pago", s["h2"]))
        instr_box = Table(
            [[Paragraph(pm.instructions.replace("\n", "<br/>"), s["mono"])]],
            colWidths=[18 * cm],
        )
        instr_box.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, -1), NES_GRAY_BG),
            ("BOX", (0, 0), (-1, -1), 0.5, NES_GRAY_LINE),
            ("LINEBEFORE", (0, 0), (0, -1), 3, NES_YELLOW),
            ("LEFTPADDING", (0, 0), (-1, -1), 14),
            ("RIGHTPADDING", (0, 0), (-1, -1), 14),
            ("TOPPADDING", (0, 0), (-1, -1), 10),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 10),
        ]))
        elements.append(instr_box)
        elements.append(Spacer(1, 8))

    # === Notas ===
    if sale.notes:
        elements.append(Paragraph("Notas", s["h2"]))
        elements.append(Paragraph(sale.notes.replace("\n", "<br/>"), s["normal"]))
        elements.append(Spacer(1, 10))

    # === Footer del documento (gracias) ===
    elements.append(Spacer(1, 14))
    elements.append(Paragraph(
        "<i>Gracias por elegir <b>ChevroCaracas</b>. Conservá esta nota de entrega como comprobante.</i>",
        s["footer"],
    ))

    return build_branded_pdf(
        elements,
        title="Nota de entrega",
        subtitle=sale.number,
    )
