// ROCA GOLF — Reportes view (conectado a API)

const FAMILY_COLORS = ["#1a4d2e","#c9a961","#2d6a44","#a88838","#4a8a63","#0d2818","#7c9885","#b22222"];

const MESES_CORTOS = ["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"];

function ReportsKpiCard({ label, value, sub }) {
  return (
    <div className="rg-kpi" style={{ padding: "14px 16px" }}>
      <div className="label" style={{ fontSize: 10.5 }}>{label}</div>
      <div className="value" style={{ fontSize: 22, marginTop: 6 }}>
        {typeof value === "string" && value.startsWith("$")
          ? <><span className="currency">$</span>{value.slice(1)}</>
          : value}
      </div>
      {sub && (
        <div style={{
          fontSize: 11, color: "var(--rg-muted)", marginTop: 4,
          fontFamily: "var(--rg-font-mono)"
        }}>{sub}</div>
      )}
    </div>
  );
}

// Línea: gasto mensual
function MonthlyChart({ data }) {
  // data: [{ mes: 1..12, total: number }]  — si no hay datos, muestra vacío
  const rows = data && data.length
    ? data
    : MESES_CORTOS.map((_, i) => ({ mes: i + 1, total: 0 }));

  const W = 720, H = 220, pad = { l: 48, r: 12, t: 16, b: 28 };
  const values = rows.map(d => d.total);
  const max = Math.max(...values, 1);
  const min = 0;
  const span = max - min || 1;
  const stepX = (W - pad.l - pad.r) / (rows.length - 1);
  const yFor  = v => pad.t + (1 - (v - min) / span) * (H - pad.t - pad.b);
  const xFor  = i => pad.l + i * stepX;
  const points = rows.map((d, i) => `${xFor(i)},${yFor(d.total)}`).join(" ");
  const areaPts = `${xFor(0)},${H - pad.b} ${points} ${xFor(rows.length - 1)},${H - pad.b}`;
  const ticks = [0, max * 0.5, max];

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }}>
      {ticks.map((t, i) => (
        <g key={i}>
          <line x1={pad.l} y1={yFor(t)} x2={W - pad.r} y2={yFor(t)}
            stroke="var(--rg-line)" strokeDasharray="2 4"/>
          <text x={pad.l - 8} y={yFor(t) + 3.5} fontSize="10" fill="var(--rg-muted)"
            textAnchor="end" fontFamily="var(--rg-font-mono)">
            {t >= 1000 ? `$${(t / 1000).toFixed(0)}k` : `$${Math.round(t)}`}
          </text>
        </g>
      ))}
      <polygon points={areaPts} fill="var(--rg-green-700)" opacity="0.10"/>
      <polyline points={points} fill="none" stroke="var(--rg-green-700)"
        strokeWidth="2" strokeLinejoin="round"/>
      {rows.map((d, i) => (
        <g key={i}>
          <circle cx={xFor(i)} cy={yFor(d.total)} r="3.5"
            fill="var(--rg-paper)" stroke="var(--rg-green-700)" strokeWidth="1.6"/>
          <text x={xFor(i)} y={H - pad.b + 16} fontSize="10.5"
            fill="var(--rg-muted)" textAnchor="middle">
            {MESES_CORTOS[(d.mes - 1) % 12]}
          </text>
        </g>
      ))}
      <circle cx={xFor(rows.length - 1)} cy={yFor(rows[rows.length - 1].total)}
        r="6" fill="var(--rg-gold)" opacity="0.35"/>
    </svg>
  );
}

// Donut: status de pago
function StatusDonut({ ordenes }) {
  const totals = ordenes.reduce((acc, o) => {
    if (o.moneda !== "MXN") return acc;
    if (o.statuspago === "PAGADO") {
      acc.pagado += o.total;
    } else if (o.statuspago === "PAGO_PARCIAL") {
      acc.pagado    += o.montopagado;
      acc.parcial   += o.montopendiente;
    } else {
      acc.pendiente += o.total;
    }
    return acc;
  }, { pagado: 0, parcial: 0, pendiente: 0 });

  const segs = [
    { k: "Pagado",    v: totals.pagado,    c: "var(--rg-flag-ok)"   },
    { k: "Parcial",   v: totals.parcial,   c: "var(--rg-flag-warn)" },
    { k: "Pendiente", v: totals.pendiente, c: "var(--rg-flag-over)" }
  ];
  const sum = segs.reduce((a, s) => a + s.v, 0) || 1;
  const r = 56, circ = 2 * Math.PI * r;
  let off = 0;

  return (
    <div className="rg-donut-wrap">
      <svg width="140" height="140" viewBox="0 0 140 140">
        <circle cx="70" cy="70" r={r} fill="none" stroke="var(--rg-line)" strokeWidth="14"/>
        {segs.map(s => {
          const len  = (s.v / sum) * circ;
          const dash = `${len} ${circ - len}`;
          const el   = (
            <circle key={s.k} cx="70" cy="70" r={r} fill="none"
              stroke={s.c} strokeWidth="14"
              strokeDasharray={dash} strokeDashoffset={-off}
              transform="rotate(-90 70 70)"/>
          );
          off += len;
          return el;
        })}
        <text x="70" y="68" textAnchor="middle" fontFamily="var(--rg-font-display)"
          fontSize="18" fontWeight="600" fill="var(--rg-ink)">
          {sum >= 1000 ? `$${(sum / 1000).toFixed(0)}K` : `$${Math.round(sum)}`}
        </text>
        <text x="70" y="84" textAnchor="middle" fontSize="9.5"
          fill="var(--rg-muted)" letterSpacing="0.1em">TOTAL MXN</text>
      </svg>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, flex: 1 }}>
        {segs.map(s => (
          <div className="rg-row" key={s.k} style={{ justifyContent: "space-between" }}>
            <div className="rg-row" style={{ gap: 8 }}>
              <span className="rg-dot" style={{ background: s.c }}/>
              <span style={{ fontSize: 12 }}>{s.k}</span>
            </div>
            <span className="rg-mono" style={{ fontSize: 12, fontWeight: 600 }}>
              ${fmtMoney(s.v, { compact: true })}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Horizontal bars: top proveedores
function TopProveedoresChart({ proveedores }) {
  const sorted = (proveedores || [])
    .filter(p => p.activo)
    .slice()
    .sort((a, b) => (b.monto || 0) - (a.monto || 0))
    .slice(0, 6);
  const max = Math.max(...sorted.map(s => s.monto || 0), 1);

  if (!sorted.length) {
    return (
      <div style={{ padding: "32px 24px", textAlign: "center", color: "var(--rg-muted)", fontSize: 13 }}>
        Sin proveedores con órdenes registradas.
      </div>
    );
  }

  return (
    <div style={{ padding: "16px 20px", display: "flex", flexDirection: "column", gap: 11 }}>
      {sorted.map((p, i) => (
        <div key={p.id} style={{
          display: "grid",
          gridTemplateColumns: "20px minmax(0,1fr) 100px",
          gap: 10, alignItems: "center"
        }}>
          <span style={{ fontFamily: "var(--rg-font-mono)", fontSize: 11, color: "var(--rg-muted)" }}>
            #{i + 1}
          </span>
          <div>
            <div style={{
              fontSize: 12, fontWeight: 500, marginBottom: 4,
              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"
            }}>{p.nombre}</div>
            <div className="rg-bar-track">
              <div className="fill" style={{
                width: ((p.monto || 0) / max * 100) + "%",
                background: i === 0 ? "var(--rg-green-700)"
                          : i === 1 ? "var(--rg-green-600)"
                          : "var(--rg-green-500)"
              }}/>
            </div>
          </div>
          <span className="rg-mono" style={{ fontSize: 12, fontWeight: 600, textAlign: "right" }}>
            ${fmtMoney(p.monto || 0)}
          </span>
        </div>
      ))}
    </div>
  );
}

// Por familia (gasto + barra presupuesto)
function FamilyTable({ familias, thresholds }) {
  const total = familias.reduce((a, f) => a + (f.spent || 0), 0) || 1;
  const sorted = familias.slice().sort((a, b) => (b.spent || 0) - (a.spent || 0));

  if (!sorted.length) {
    return (
      <div style={{ padding: "32px 24px", textAlign: "center", color: "var(--rg-muted)", fontSize: 13 }}>
        Sin datos de gasto por familia.
      </div>
    );
  }

  return (
    <div>
      {sorted.map((f) => {
        const nombre = f.nombre || f.name || "—";
        const codigo = f.codigo || f.id  || "?";
        const spent  = f.spent  || 0;
        const budget = f.budget || 0;
        const pct    = budget > 0 ? (spent / budget) * 100 : 0;
        const lv     = flagLevel(pct, thresholds);
        const share  = (spent / total) * 100;
        return (
          <div key={codigo} style={{
            display: "grid",
            gridTemplateColumns: "26px minmax(0,1.3fr) 1fr 80px",
            gap: 14, alignItems: "center",
            padding: "12px 18px",
            borderBottom: "1px solid var(--rg-line)"
          }}>
            <GolfFlag level={lv} size={22} animate={false}/>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>{nombre}</div>
              <div style={{
                fontSize: 10.5, color: "var(--rg-muted)",
                fontFamily: "var(--rg-font-mono)", marginTop: 2
              }}>Familia {codigo}</div>
            </div>
            <div>
              <div style={{
                display: "flex", justifyContent: "space-between",
                fontSize: 11, color: "var(--rg-muted)",
                fontFamily: "var(--rg-font-mono)", marginBottom: 4
              }}>
                <span>${fmtMoney(spent)}</span>
                <span>{share.toFixed(1)}% del total</span>
              </div>
              <div className="rg-track">
                <div className={"fill " + lv} style={{ width: Math.min(pct, 100) + "%" }}/>
              </div>
            </div>
            <div className="rg-mono" style={{
              fontWeight: 600, textAlign: "right", color: flagColor(lv)
            }}>{pct.toFixed(0)}%</div>
          </div>
        );
      })}
    </div>
  );
}

function ReportsView({ thresholds, setThresholds, onNav }) {
  const { ordenes, familias, proveedores, alerts, reportes, loadReportes, loading } = useAppData();

  // Cargar reportes cuando se monta la vista
  useEffect(() => { loadReportes(); }, []);

  const alertCount = alerts.filter(a => a.level !== "ok").length;

  // KPIs calculados desde ordenes
  const totalMxn  = ordenes.filter(o => o.moneda === "MXN").reduce((a, o) => a + (o.total || 0), 0);
  const totalUsd  = ordenes.filter(o => o.moneda === "USD").reduce((a, o) => a + (o.total || 0), 0);
  const pendiente = ordenes.reduce((a, o) => a + (o.montopendiente || 0), 0);
  const pagado    = ordenes.reduce((a, o) => a + (o.montopagado    || 0), 0);
  const criticas  = ordenes.filter(o => o.prioridad === "CRITICO").length;

  // Datos mensuales desde reportes API (si están disponibles)
  const mensual = reportes ? reportes.mensual : null;

  return (
    <div className="rg-app">
      <Sidebar active="reports" onNav={onNav} alertCount={alertCount}/>
      <main className="rg-main" style={{ position: "relative" }}>
        {loading && <LoadingOverlay/>}
        <Topbar crumbs="Compras / Reportes" title="Reportes y estadísticas"
          actions={<button className="rg-btn primary">{Icon.excel()} Exportar Excel</button>}/>
        <div className="rg-content">

          {/* Filtros de periodo */}
          <div className="rg-filter-bar"
            style={{ gridTemplateColumns: "1fr 130px 130px 200px auto auto" }}>
            <div className="rg-field">
              <label>Periodo</label>
              <div className="rg-row">
                <span className="rg-pill">{new Date().getFullYear()}</span>
              </div>
            </div>
            <div className="rg-field">
              <label>Desde</label>
              <input className="rg-input" type="date"/>
            </div>
            <div className="rg-field">
              <label>Hasta</label>
              <input className="rg-input" type="date"/>
            </div>
            <div className="rg-field">
              <label>Proyecto</label>
              <select className="rg-select" defaultValue="">
                <option value="">Todos</option>
              </select>
            </div>
            <button className="rg-btn primary" style={{ height: 32 }}>
              {Icon.filter()} Filtrar
            </button>
            <button className="rg-btn" style={{ height: 32 }}>
              {Icon.x()} Limpiar
            </button>
          </div>

          {/* KPIs */}
          <div className="rg-kpi-grid" style={{ gridTemplateColumns: "repeat(6, 1fr)" }}>
            <ReportsKpiCard label="Total OCs"  value={ordenes.length} sub="este periodo"/>
            <ReportsKpiCard label="Total MXN"  value={"$" + fmtMoney(totalMxn)} sub="en pesos"/>
            <ReportsKpiCard label="Total USD"  value={"$" + fmtMoney(totalUsd) + " USD"} sub="en dólares"/>
            <ReportsKpiCard label="Pendiente"  value={"$" + fmtMoney(pendiente)} sub="por pagar"/>
            <ReportsKpiCard label="Pagado"     value={"$" + fmtMoney(pagado)} sub="liquidado"/>
            <ReportsKpiCard label="Críticas"   value={criticas} sub="prioridad alta"/>
          </div>

          {/* Gráficas principales */}
          <div className="rg-chart-row">
            <div className="rg-card">
              <div className="rg-card-header">
                <div>
                  <h3>Gasto mensual MXN</h3>
                  <div className="sub">
                    {mensual ? "Datos reales de la base de datos" : "Cargando gráfica…"}
                  </div>
                </div>
              </div>
              <div style={{ padding: "16px 18px 18px" }}>
                <MonthlyChart data={mensual}/>
              </div>
            </div>
            <div className="rg-card">
              <div className="rg-card-header">
                <div>
                  <h3>Status de pago</h3>
                  <div className="sub">Distribución MXN</div>
                </div>
              </div>
              <StatusDonut ordenes={ordenes}/>
            </div>
          </div>

          {/* Familia + Top proveedores */}
          <div className="rg-two-col">
            <div className="rg-card">
              <div className="rg-card-header">
                <div>
                  <h3>Gasto por familia de insumos</h3>
                  <div className="sub">{familias.length} familias · {ordenes.length} OCs</div>
                </div>
                <span className="rg-pill">vs presupuesto</span>
              </div>
              <FamilyTable familias={familias} thresholds={thresholds}/>
            </div>
            <div className="rg-card">
              <div className="rg-card-header">
                <div>
                  <h3>Top proveedores</h3>
                  <div className="sub">Por monto ejercido</div>
                </div>
              </div>
              <TopProveedoresChart proveedores={proveedores}/>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { ReportsView, FAMILY_COLORS });
