"""PDF de detalle de una transferencia entre sedes."""
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 StockTransfer
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,
)


def _status_badge(label: str, status: str):
    """Mini badge para el estado de la transferencia."""
    s = styles()
    color_map = {
        "DRAFT": ("#fef3c7", "#92400e"),
        "IN_TRANSIT": ("#dbeafe", "#1e40af"),
        "RECEIVED_PENDING": ("#fde68a", "#78350f"),
        "RECEIVED": ("#d1fae5", "#065f46"),
        "CANCELLED": ("#e5e7eb", "#374151"),
    }
    bg, fg = color_map.get(status, ("#e5e7eb", "#374151"))
    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), 8),
        ("RIGHTPADDING", (0, 0), (-1, -1), 8),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("BOX", (0, 0), (-1, -1), 0.5, colors.HexColor(fg)),
    ]))
    return badge


STATUS_LABEL = {
    "DRAFT": "Borrador",
    "IN_TRANSIT": "En tránsito",
    "RECEIVED_PENDING": "Recepción confirmada",
    "RECEIVED": "Recibida",
    "CANCELLED": "Cancelada",
}


def render_transfer_pdf(t: StockTransfer) -> io.BytesIO:
    s = styles()
    elements = []

    status_raw = t.status.value if hasattr(t.status, "value") else str(t.status)
    status_label = STATUS_LABEL.get(status_raw.upper(), status_raw)

    # === Bloque de estado destacado arriba ===
    elements.append(_status_badge(status_label, status_raw.upper()))
    elements.append(Spacer(0, 12))

    # === Bloque info: origen / destino ===
    from_label = Paragraph(
        f'<font color="#6b6b76" size="7"><b>SEDE ORIGEN</b></font><br/>'
        f'<font size="11"><b>{t.from_store.code if t.from_store else "?"}</b></font><br/>'
        f'<font size="9">{t.from_store.name if t.from_store else "—"}</font>',
        s["normal"],
    )
    arrow = Paragraph(
        '<para align="center"><font size="20" color="#FCD90A"><b>→</b></font></para>',
        s["normal"],
    )
    to_label = Paragraph(
        f'<font color="#6b6b76" size="7"><b>SEDE DESTINO</b></font><br/>'
        f'<font size="11"><b>{t.to_store.code if t.to_store else "?"}</b></font><br/>'
        f'<font size="9">{t.to_store.name if t.to_store else "—"}</font>',
        s["normal"],
    )
    route_table = Table([[from_label, arrow, to_label]], colWidths=[None, 2 * cm, None])
    route_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), NES_GRAY_BG),
        ("BOX", (0, 0), (-1, -1), 0.5, NES_GRAY_LINE),
        ("LEFTPADDING", (0, 0), (-1, -1), 14),
        ("RIGHTPADDING", (0, 0), (-1, -1), 14),
        ("TOPPADDING", (0, 0), (-1, -1), 12),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 12),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ]))
    elements.append(route_table)
    elements.append(Spacer(0, 14))

    # === Bloque de responsables y fechas ===
    def _person_block(label: str, user, dt):
        name = user.full_name if user else "—"
        when = dt.strftime("%Y-%m-%d %H:%M") if dt else ""
        return Paragraph(
            f'<font color="#6b6b76" size="7"><b>{label.upper()}</b></font><br/>'
            f'<font size="9"><b>{name}</b></font><br/>'
            f'<font size="8" color="#8a8a93">{when}</font>',
            s["normal"],
        )

    people = [
        _person_block("Creada por", t.user, t.created_at),
        _person_block("Enviada por", t.sent_by, t.sent_at),
        _person_block("Responsable designado", t.assigned_receiver, None),
        _person_block("Recibida por", t.received_by, t.received_at),
    ]
    people_table = Table([people], colWidths=[None, None, None, None])
    people_table.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), colors.white),
        ("BOX", (0, 0), (-1, -1), 0.5, NES_GRAY_LINE),
        ("INNERGRID", (0, 0), (-1, -1), 0.5, NES_GRAY_LINE),
        ("LEFTPADDING", (0, 0), (-1, -1), 12),
        ("RIGHTPADDING", (0, 0), (-1, -1), 12),
        ("TOPPADDING", (0, 0), (-1, -1), 10),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 10),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
    ]))
    elements.append(people_table)
    elements.append(Spacer(0, 14))

    # === Notas ===
    if t.notes:
        elements.append(Paragraph(
            f'<font color="#6b6b76" size="8"><b>NOTAS DE LA TRANSFERENCIA</b></font>',
            s["normal"],
        ))
        elements.append(Spacer(0, 4))
        elements.append(Paragraph(
            t.notes.replace("\n", "<br/>"),
            s["normal"],
        ))
        elements.append(Spacer(0, 10))

    if t.receive_notes:
        elements.append(Paragraph(
            f'<font color="#6b6b76" size="8"><b>OBSERVACIONES DE RECEPCIÓN</b></font>',
            s["normal"],
        ))
        elements.append(Spacer(0, 4))
        elements.append(Paragraph(
            t.receive_notes.replace("\n", "<br/>"),
            s["normal"],
        ))
        elements.append(Spacer(0, 10))

    # === Tabla de unidades ===
    elements.append(Paragraph(
        f'<font size="11"><b>Unidades transferidas ({len(t.items) if t.items else 0})</b></font>',
        s["normal"],
    ))
    elements.append(Spacer(0, 6))

    header = ["#", "Producto", "Serial", "Código de barras", "Recibida"]
    rows = [header]
    for i, it in enumerate(t.items or [], start=1):
        unit = it.product_item
        rows.append([
            str(i),
            unit.product.name if unit and unit.product else "—",
            unit.serial if unit else "—",
            unit.barcode if unit else "—",
            "✓" if it.received else "—",
        ])

    if len(rows) == 1:
        elements.append(Paragraph(
            '<para align="center"><font color="#6b6b76">Sin unidades.</font></para>',
            s["normal"],
        ))
    else:
        items_table = Table(rows, colWidths=[1 * cm, None, 4 * cm, 4 * cm, 2 * cm])
        items_table.setStyle(data_table_style())
        items_table.setStyle(TableStyle([
            ("ALIGN", (0, 1), (0, -1), "CENTER"),
            ("ALIGN", (4, 1), (4, -1), "CENTER"),
            ("FONTNAME", (2, 1), (3, -1), "Courier"),
        ]))
        elements.append(items_table)

    return build_branded_pdf(
        elements,
        title=f"Transferencia {t.number}",
        subtitle=f"{(t.from_store.code if t.from_store else '?')} → {(t.to_store.code if t.to_store else '?')} · {status_label}",
        watermark=False,
    )
