"""Finance routes.

Moved from app.admin_dashboard in v4.7.2. The handlers still reuse
legacy helpers to keep this refactor behavior-preserving.
"""
from fastapi import APIRouter
from urllib.parse import quote
import app.admin_dashboard as legacy
from app.admin_dashboard import *  # noqa: F401,F403

router = APIRouter()


@router.get("/finance", response_class=HTMLResponse)
@router.get("/financeiro", response_class=HTMLResponse)
async def finance_page(q: Optional[str] = None):
    finance_tasks = list_tasks(status=None, route="financeiro", q=q, limit=200)
    return_to = "/finance" + (f"?q={quote(str(q), safe='')}" if q else "")
    finance_actions = {"SEND_PROFORMA", "SEND_INVOICE", "CONFIRM_PAYMENT"}
    finance_tasks = [t for t in finance_tasks if str(t.get("action_code") or "") in finance_actions or str(t.get("route") or "") == "financeiro"]
    opportunities = list_opportunities(status="all", q=q, limit=300)
    payment_opps = [o for o in opportunities if str(o.get("stage") or "") in {"PROFORMA_REQUESTED", "PROFORMA_SENT", "INVOICE_REQUESTED", "INVOICE_SENT", "WAITING_PAYMENT", "PAYMENT_CONFIRMED"}]

    rows = ""
    for task in finance_tasks[:80]:
        tid = str(task.get("id") or "")
        customer = customer_display(task)
        code = str(task.get("action_code") or "")
        rows += f"""
        <tr>
          <td><a class="cf-row-link" href="/tasks/{esc(tid)}?return_to={quote(return_to, safe='')}">{esc(action_label(code))}</a><div class="small"><code>{esc(code)}</code></div></td>
          <td><strong>{esc(customer)}</strong><div class="small text-secondary text-break">{esc(task.get('customer_email') or '')}</div></td>
          <td>{status_badge(task.get('status'))}</td>
          <td>{esc(task.get('created_at') or '—')}</td>
          <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="/tasks/{esc(tid)}?return_to={quote(return_to, safe='')}">Abrir</a></td>
        </tr>
        """
    if not rows:
        rows = '<tr><td colspan="5" class="text-center text-secondary py-5">Sem tarefas financeiras.</td></tr>'

    body = f"""
    <section class="cf-kpi-grid">
      {kpi_card('Tarefas financeiras', len(finance_tasks), '/finance', 'ativas/histórico', 'bi-list-check')}
      {kpi_card('A aguardar pagamento', sum(1 for o in payment_opps if str(o.get('stage')) == 'WAITING_PAYMENT'), '/opportunities', 'oportunidades', 'bi-hourglass-split', 'cf-kpi-tone-orange')}
      {kpi_card('Pendentes', sum(1 for t in finance_tasks if str(t.get('status')) == 'pending'), '/tasks?status=pending&route=financeiro', 'abrir tarefas', 'bi-list-check')}
      {kpi_card('Pagamentos confirmados', sum(1 for o in payment_opps if str(o.get('stage')) == 'PAYMENT_CONFIRMED'), '/opportunities', 'seguir para envio', 'bi-check2-circle', 'cf-kpi-tone-green')}
    </section>
    <div class="d-flex justify-content-end mb-3"><a class="btn btn-outline-primary" href="/finance/forecast"><i class="bi bi-graph-up-arrow"></i> Meta e desempenho comercial</a></div>
    <section class="card cf-card cf-filter-card"><form method="get" action="/finance" class="row g-3 align-items-end"><div class="col-lg-8"><label class="form-label small fw-bold text-secondary">Procurar</label><input class="form-control" type="search" name="q" value="{esc(q or '')}" placeholder="cliente, fatura, pagamento..."></div><div class="col-lg-4 d-flex gap-2"><button class="btn btn-primary flex-fill" type="submit">Filtrar</button><a class="btn btn-outline-secondary" href="/finance">Limpar</a></div></form></section>
    <section class="card cf-card"><div class="card-body p-0"><div class="p-3 border-bottom"><h2 class="cf-section-title">Financeiro operacional</h2><div class="small text-secondary">Orçamentos, faturas e pagamentos a tratar.</div></div><div class="cf-table-wrap border-0 rounded-0"><table class="table cf-table"><thead><tr><th>Ação</th><th>Cliente</th><th>Estado</th><th>Criada</th><th></th></tr></thead><tbody>{rows}</tbody></table></div></div></section>
    """
    return layout("Financeiro", "O que falta faturar ou confirmar?", body, "finance")


