"""PDF: inventario por almacén — para auditorías físicas."""
from __future__ import annotations

import io
from collections import defaultdict
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 Warehouse
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) -> str:
    if amount is None:
        return "—"
    return f"$ {Decimal(amount):,.2f}"


def build_warehouse_inventory_pdf(warehouse: Warehouse, items: list, show_cost: bool = True) -> io.BytesIO:
    """`show_cost`: si es False, omite la columna Costo y el KPI 'Valor inventario'
    (dato sensible — solo para quien tiene `costs.view`)."""
    s = styles()
    elements: list = []

    # Cabecera de info del almacén
    info_lines = ['<font name="Helvetica-Bold" color="#0E0E14">ALMACÉN</font>',
                  f'<font name="Helvetica-Bold">{warehouse.code} · {warehouse.name}</font>']
    if warehouse.store:
        info_lines.append(f"Sede: {warehouse.store.code} · {warehouse.store.name}")
    if warehouse.notes:
        info_lines.append(warehouse.notes)
    if warehouse.is_default:
        info_lines.append('<font color="#1d8348"><b>★ Almacén por defecto</b></font>')

    # KPIs en banda. El reporte solo trae unidades DISPONIBLES (stock real),
    # así que los conteos y el valor son sobre lo disponible.
    total_units = len(items)
    total_value = sum((Decimal(it.cost) for it in items if it.cost), Decimal("0"))
    products_distinct = len({it.product_id for it in items})

    info_table = Table(
        [[Paragraph("<br/>".join(info_lines), s["normal"])]],
        colWidths=[18 * cm],
    )
    info_table.setStyle(info_card_style())
    elements.append(info_table)
    elements.append(Spacer(1, 12))

    kpi_cells = [
        Paragraph(f"<b>Unidades disponibles</b><br/>{total_units}", s["small"]),
        Paragraph(f"<b>Productos distintos</b><br/>{products_distinct}", s["small"]),
    ]
    if show_cost:
        kpi_cells.append(Paragraph(f"<b>Valor inventario</b><br/>{_money(total_value)}", s["small"]))
    kpi_row = Table([kpi_cells], colWidths=[3.0 * cm] * len(kpi_cells))
    kpi_row.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(kpi_row)
    elements.append(Spacer(1, 14))

    # Tabla de unidades agrupadas por ubicación
    elements.append(Paragraph("Unidades disponibles en este almacén", s["h2"]))

    if not items:
        elements.append(Paragraph("Sin stock disponible en este almacén.", s["small"]))
    else:
        # Agrupar por ubicación
        groups = defaultdict(list)
        for it in items:
            loc_key = it.location_ref.code if it.location_ref else None
            groups[loc_key].append(it)

        for loc_code in sorted(groups.keys(), key=lambda x: (x is None, x or "")):
            sub_items = groups[loc_code]
            label = loc_code if loc_code else "Sin ubicación"
            elements.append(Spacer(1, 6))
            elements.append(Paragraph(
                f'<font name="Helvetica-Bold" color="#0E0E14">📍 {label}</font> '
                f'<font color="#6b6b76">· {len(sub_items)} unidad{"es" if len(sub_items) > 1 else ""}</font>',
                s["small"],
            ))
            header = ["#", "Producto", "Serial", "Código", "Status"]
            if show_cost:
                header.append("Costo")
            data = [header]
            for idx, it in enumerate(sub_items, start=1):
                st = it.status.value if hasattr(it.status, "value") else it.status
                row = [
                    str(idx),
                    Paragraph(it.product.name if it.product else "—", s["normal"]),
                    Paragraph(f"<font name='Courier'>{it.serial}</font>", s["small"]),
                    Paragraph(f"<font name='Courier'>{it.barcode}</font>", s["small"]),
                    st,
                ]
                if show_cost:
                    row.append(_money(it.cost))
                data.append(row)
            col_widths = [0.7 * cm, 6.8 * cm, 3.3 * cm, 3.3 * cm, 2.0 * cm]
            if show_cost:
                col_widths.append(1.9 * cm)
            tbl = Table(data, colWidths=col_widths, repeatRows=1)
            style = data_table_style()
            style.add("ALIGN", (0, 1), (0, -1), "CENTER")
            if show_cost:
                style.add("ALIGN", (5, 1), (5, -1), "RIGHT")
            tbl.setStyle(style)
            elements.append(tbl)

    elements.append(Spacer(1, 16))
    elements.append(Paragraph(
        "<i>Inventario emitido por <b>ChevroCaracas</b> · imprimí esta hoja para tu auditoría física.</i>",
        s["footer"],
    ))

    return build_branded_pdf(
        elements,
        title="Inventario por almacén",
        subtitle=f"{warehouse.code} · {warehouse.store.code if warehouse.store else ''}",
    )
