"""PDF: estado de cuenta del cliente (sales + receivables)."""
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 (
    AccountReceivable,
    Customer,
    ReceivableStatus,
    Sale,
)
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 _kpi(label: str, value: str, highlight: bool = False) -> Table:
    s = styles()
    label_p = Paragraph(label.upper(), s["label"])
    value_color = "#dc2626" if highlight else "#0E0E14"
    value_p = Paragraph(
        f'<font color="{value_color}" size="14"><b>{value}</b></font>', s["normal"],
    )
    t = Table([[label_p], [value_p]], colWidths=[None])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), NES_GRAY_BG if not highlight else colors.HexColor("#fce4e4")),
        ("BOX", (0, 0), (-1, -1), 0.5, NES_GRAY_LINE if not highlight else colors.HexColor("#dc2626")),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("RIGHTPADDING", (0, 0), (-1, -1), 10),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ]))
    return t


def build_customer_statement_pdf(customer: Customer, sales: list[Sale],
                                  receivables: list[AccountReceivable], summary: dict) -> io.BytesIO:
    s = styles()
    elements: list = []

    # === Cabecera del cliente ===
    info_lines = ['<font name="Helvetica-Bold" color="#0E0E14">CLIENTE</font>',
                  f'<font name="Helvetica-Bold">{customer.name}</font>']
    if customer.document:
        info_lines.append(f"Doc: {customer.document}")
    if customer.email:
        info_lines.append(customer.email)
    if customer.phone:
        info_lines.append(f"Tel: {customer.phone}")
    if customer.address:
        info_lines.append(customer.address)
    if customer.city or customer.state:
        info_lines.append(f"{customer.city or ''}{', ' + customer.state if customer.state else ''}")

    cust_table = Table(
        [[Paragraph("<br/>".join(info_lines), s["normal"])]],
        colWidths=[18 * cm],
    )
    cust_table.setStyle(info_card_style())
    elements.append(cust_table)
    elements.append(Spacer(1, 12))

    # === KPIs (4 columnas) ===
    balance = Decimal(summary.get("balance", 0))
    overdue_amount = Decimal(summary.get("overdue_amount", 0))
    kpi_row = Table(
        [[
            _kpi("Compras totales", str(summary.get("sale_count", 0))),
            _kpi("Facturado", _money(summary.get("total"))),
            _kpi("Pagado", _money(summary.get("paid"))),
            _kpi("Saldo pendiente", _money(balance), highlight=balance > 0),
        ]],
        colWidths=[4.5 * cm] * 4,
    )
    kpi_row.setStyle(TableStyle([
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("LEFTPADDING", (0, 0), (-1, -1), 0),
        ("RIGHTPADDING", (0, 0), (-1, -1), 4),
    ]))
    elements.append(kpi_row)
    elements.append(Spacer(1, 6))

    if overdue_amount > 0:
        warn = Table(
            [[Paragraph(
                f'<b>⚠ {summary.get("overdue_count", 0)} cuenta(s) vencida(s)</b> · monto vencido { _money(overdue_amount) }',
                s["callout"],
            )]],
            colWidths=[18 * cm],
        )
        warn.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#fdebd0")),
            ("BOX", (0, 0), (-1, -1), 0.8, colors.HexColor("#b9770e")),
            ("TEXTCOLOR", (0, 0), (-1, -1), colors.HexColor("#b9770e")),
            ("LEFTPADDING", (0, 0), (-1, -1), 12),
            ("TOPPADDING", (0, 0), (-1, -1), 6),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ]))
        elements.append(warn)
    elements.append(Spacer(1, 14))

    # === Ventas ===
    elements.append(Paragraph("Ventas", s["h2"]))
    if not sales:
        elements.append(Paragraph("Sin ventas registradas.", s["small"]))
    else:
        sale_data = [["Número", "Fecha", "Canal", "Estado", "Pago", "Total"]]
        for sl in sales:
            channel = sl.channel.value.upper() if hasattr(sl.channel, "value") else str(sl.channel).upper()
            status = sl.status.value if hasattr(sl.status, "value") else str(sl.status)
            pay_status = sl.payment_status.value if hasattr(sl.payment_status, "value") else str(sl.payment_status)
            sale_data.append([
                Paragraph(f"<font name='Courier'>{sl.number}</font>", s["small"]),
                sl.created_at.strftime("%Y-%m-%d"),
                channel,
                status,
                pay_status,
                _money(sl.total, sl.currency),
            ])
        sale_table = Table(
            sale_data,
            colWidths=[3.0 * cm, 2.4 * cm, 2.0 * cm, 3.0 * cm, 3.0 * cm, 4.6 * cm],
            repeatRows=1,
        )
        st = data_table_style()
        st.add("ALIGN", (5, 1), (5, -1), "RIGHT")
        sale_table.setStyle(st)
        elements.append(sale_table)
    elements.append(Spacer(1, 14))

    # === Cuentas por cobrar ===
    elements.append(Paragraph("Cuentas por cobrar", s["h2"]))
    if not receivables:
        elements.append(Paragraph("Sin cuentas por cobrar.", s["small"]))
    else:
        ar_data = [["Venta", "Fecha", "Vence", "Estado", "Total", "Pagado", "Saldo"]]
        for ar in receivables:
            status = ar.status.value if hasattr(ar.status, "value") else str(ar.status)
            sale_num = ar.sale.number if ar.sale else "—"
            balance = Decimal(ar.total) - Decimal(ar.paid)
            ar_data.append([
                Paragraph(f"<font name='Courier'>{sale_num}</font>", s["small"]),
                ar.created_at.strftime("%Y-%m-%d"),
                ar.due_date.strftime("%Y-%m-%d") if ar.due_date else "—",
                status,
                _money(ar.total, ar.currency),
                _money(ar.paid, ar.currency),
                _money(balance, ar.currency),
            ])
        ar_table = Table(
            ar_data,
            colWidths=[3.0 * cm, 2.2 * cm, 2.2 * cm, 2.4 * cm, 2.7 * cm, 2.7 * cm, 2.8 * cm],
            repeatRows=1,
        )
        st = data_table_style()
        st.add("ALIGN", (4, 1), (-1, -1), "RIGHT")
        ar_table.setStyle(st)
        elements.append(ar_table)

    elements.append(Spacer(1, 18))
    elements.append(Paragraph(
        "<i>Estado de cuenta generado por <b>ChevroCaracas</b>.</i>",
        s["footer"],
    ))

    return build_branded_pdf(
        elements,
        title="Estado de cuenta",
        subtitle=f"Cliente · {customer.name}",
    )
