// Reports — manager dashboard with charts for decision-making

const ReportsPage = () => {
  const { SAIF_COMPANIES, SUPPLIERS, DOCUMENTS, POS, PROPOSALS, TICKETS } = window.SaifData;
  const [period, setPeriod] = React.useState('q2');

  // === Aggregations ===

  // Spend by company (sum of PO values)
  const spendByCo = SAIF_COMPANIES.map(c => ({
    co: c,
    total: POS.filter(p => p.company === c.id).reduce((s, p) => s + p.amount, 0),
  })).sort((a, b) => b.total - a.total);

  // Document health per company
  const docHealthByCo = SAIF_COMPANIES.map(c => {
    const cosup = SUPPLIERS.filter(s => s.companies.includes(c.id)).map(s => s.id);
    const docs = DOCUMENTS.filter(d => cosup.includes(d.supplierId));
    return {
      co: c,
      green: docs.filter(d => d.status === 'green').length,
      amber: docs.filter(d => d.status === 'amber').length,
      red:   docs.filter(d => d.status === 'red').length,
    };
  });

  // Supplier proposals pipeline funnel
  const supPropsByStatus = (status) => PROPOSALS.filter(p => p.kind === 'supplier' && p.status === status).length;
  const funnel = [
    { stage: 'Submitted',         count: PROPOSALS.filter(p => p.kind === 'supplier').length, color: 'oklch(0.55 0.10 235)' },
    { stage: 'Under review',      count: supPropsByStatus('under-review') + supPropsByStatus('submitted'), color: 'oklch(0.62 0.13 55)' },
    { stage: 'Revision iterating', count: supPropsByStatus('revision-requested') + supPropsByStatus('resubmitted'), color: 'oklch(0.74 0.13 75)' },
    { stage: 'Approved',          count: supPropsByStatus('approved'), color: 'oklch(0.62 0.12 145)' },
  ];

  // Top suppliers by open value
  const topSuppliers = [...SUPPLIERS]
    .filter(s => s.status === 'approved')
    .sort((a, b) => b.openValue - a.openValue)
    .slice(0, 5);

  // Tickets by priority (active only)
  const activeTickets = TICKETS.filter(t => t.status !== 'resolved' && t.status !== 'closed');
  const ticketsByPriority = ['urgent', 'high', 'medium', 'low'].map(p => ({
    priority: p,
    count: activeTickets.filter(t => t.priority === p).length,
    color: p === 'urgent' ? 'var(--red)' : p === 'high' ? 'var(--amber)' : p === 'medium' ? 'var(--blue)' : 'var(--text-mute)',
  }));
  const totalTickets = ticketsByPriority.reduce((s, x) => s + x.count, 0);

  // Approval cycle time (days per stage — illustrative averages)
  const cycleTime = [
    { stage: 'Registration',     days: 1.2, color: 'var(--blue)' },
    { stage: 'Procurement Review', days: 2.4, color: 'var(--accent)' },
    { stage: 'Final Approval',   days: 3.1, color: 'var(--ink)' },
  ];

  // Monthly trend — illustrative
  const monthlyTrend = [
    { m: 'Dec', proposals: 3,  pos: 5  },
    { m: 'Jan', proposals: 5,  pos: 7  },
    { m: 'Feb', proposals: 4,  pos: 6  },
    { m: 'Mar', proposals: 7,  pos: 9  },
    { m: 'Apr', proposals: 8,  pos: 11 },
    { m: 'May', proposals: 6,  pos: 8  },
  ];

  // KPIs
  const totalSpend = spendByCo.reduce((s, x) => s + x.total, 0);
  const expiredDocs = DOCUMENTS.filter(d => d.status === 'red').length;
  const avgApprovalDays = cycleTime.reduce((s, x) => s + x.days, 0).toFixed(1);
  const winRate = Math.round((funnel[3].count / Math.max(funnel[0].count, 1)) * 100);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Reports</h1>
          <p className="page-subtitle">Decision-grade insights across spend, documents, proposals, and support.</p>
        </div>
        <div className="page-actions">
          <select className="form-control" value={period} onChange={e => setPeriod(e.target.value)} style={{ width: 130 }}>
            <option value="q2">Q2 2026</option>
            <option value="q1">Q1 2026</option>
            <option value="2026">FY 2026</option>
            <option value="2025">FY 2025</option>
          </select>
          <button className="btn"><Icon name="download" size={14}/> Export PDF</button>
        </div>
      </div>

      <div className="kpi-grid" style={{ marginBottom: 18 }}>
        <KPICard label="Total Spend" value={fmtCurrency(totalSpend)} meta="across all companies" icon="po" trend={{ dir: 'up', value: '+12%' }}/>
        <KPICard label="Avg. Approval Cycle" value={`${avgApprovalDays}d`} meta="registration → final" icon="clock" trend={{ dir: 'down', value: '-0.6d' }}/>
        <KPICard label="Doc Health" value={`${expiredDocs} expired`} meta="across all suppliers" icon="alert"/>
        <KPICard label="Proposal Win Rate" value={`${winRate}%`} meta="approved / submitted" icon="check" trend={{ dir: 'up', value: '+8%' }}/>
      </div>

      <div className="reports-grid">
        {/* Spend by company — vertical bars */}
        <div className="card report-card">
          <div className="card-header">
            <div>
              <h3 className="card-title">Spend by Company</h3>
              <div className="card-sub">Total PO value across the group</div>
            </div>
          </div>
          <div className="card-body">
            <SpendBarsChart data={spendByCo}/>
          </div>
        </div>

        {/* Proposal pipeline funnel */}
        <div className="card report-card">
          <div className="card-header">
            <div>
              <h3 className="card-title">Supplier Proposal Pipeline</h3>
              <div className="card-sub">Where proposals sit right now</div>
            </div>
          </div>
          <div className="card-body">
            <FunnelChart stages={funnel}/>
          </div>
        </div>

        {/* Document health */}
        <div className="card report-card report-card-wide">
          <div className="card-header">
            <div>
              <h3 className="card-title">Document Health by Company</h3>
              <div className="card-sub">Green = valid · Amber = expiring 30d · Red = expired</div>
            </div>
            <div style={{ display: 'flex', gap: 14, fontSize: 11 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--green)' }}></span> Valid</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--amber)' }}></span> Expiring</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--red)' }}></span> Expired</span>
            </div>
          </div>
          <div className="card-body">
            <StackedBarChart data={docHealthByCo}/>
          </div>
        </div>

        {/* Tickets by priority — donut */}
        <div className="card report-card">
          <div className="card-header">
            <div>
              <h3 className="card-title">Active Tickets by Priority</h3>
              <div className="card-sub">{totalTickets} active across the group</div>
            </div>
          </div>
          <div className="card-body" style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
            <DonutChart segments={ticketsByPriority.filter(p => p.count > 0)} total={totalTickets}/>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {ticketsByPriority.map(p => (
                <div key={p.priority} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 2, background: p.color }}></span>
                  <span style={{ flex: 1, textTransform: 'capitalize' }}>{p.priority}</span>
                  <span className="text-mono text-mute">{p.count}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Approval cycle time */}
        <div className="card report-card">
          <div className="card-header">
            <div>
              <h3 className="card-title">Avg. Approval Cycle Time</h3>
              <div className="card-sub">Days per stage (last 30 days)</div>
            </div>
          </div>
          <div className="card-body">
            <HorizontalBars items={cycleTime} unit="days" valueKey="days"/>
          </div>
        </div>

        {/* Monthly trend */}
        <div className="card report-card report-card-wide">
          <div className="card-header">
            <div>
              <h3 className="card-title">Activity Trend — Last 6 Months</h3>
              <div className="card-sub">New proposals submitted vs POs issued</div>
            </div>
            <div style={{ display: 'flex', gap: 14, fontSize: 11 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 16, height: 2, background: 'var(--accent)' }}></span> Proposals</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 16, height: 2, background: 'var(--ink)' }}></span> POs</span>
            </div>
          </div>
          <div className="card-body">
            <LineChart data={monthlyTrend}/>
          </div>
        </div>

        {/* Top suppliers leaderboard */}
        <div className="card report-card report-card-wide">
          <div className="card-header">
            <div>
              <h3 className="card-title">Top 5 Suppliers by Open Value</h3>
              <div className="card-sub">Concentration risk &mdash; track if any single supplier is too large</div>
            </div>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <table className="tbl">
              <thead><tr><th>#</th><th>Supplier</th><th>Industry</th><th style={{ textAlign: 'right' }}>Open Value</th><th style={{ width: '30%' }}>Share</th><th>POs</th></tr></thead>
              <tbody>
                {topSuppliers.map((s, i) => {
                  const share = (s.openValue / topSuppliers.reduce((sum, x) => sum + x.openValue, 0)) * 100;
                  return (
                    <tr key={s.id}>
                      <td className="text-mono text-mute">{i + 1}</td>
                      <td style={{ fontWeight: 600, color: 'var(--ink)' }}>{s.name}</td>
                      <td className="text-sm">{s.industry}</td>
                      <td className="text-mono" style={{ textAlign: 'right', fontWeight: 600 }}>{fmtCurrency(s.openValue)}</td>
                      <td>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <div style={{ flex: 1, height: 6, background: 'var(--surface-3)', borderRadius: 3, overflow: 'hidden' }}>
                            <div style={{ height: '100%', width: share + '%', background: 'var(--accent)', borderRadius: 3 }}></div>
                          </div>
                          <span className="text-mono text-xs text-mute">{share.toFixed(0)}%</span>
                        </div>
                      </td>
                      <td className="text-mono">{s.poCount}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

// === Charts (pure SVG) ===

const SpendBarsChart = ({ data }) => {
  const max = Math.max(...data.map(d => d.total)) || 1;
  const W = 460, H = 220, P = 30;
  const barW = (W - P * 2) / data.length - 14;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', maxHeight: 260 }}>
      {[0, 0.25, 0.5, 0.75, 1].map(t => (
        <g key={t}>
          <line x1={P} x2={W - P} y1={P + (1 - t) * (H - P * 2)} y2={P + (1 - t) * (H - P * 2)} stroke="var(--line-2)" strokeDasharray={t === 0 ? '0' : '2 3'}/>
        </g>
      ))}
      {data.map((d, i) => {
        const h = (d.total / max) * (H - P * 2);
        const x = P + i * ((W - P * 2) / data.length) + 7;
        const y = H - P - h;
        return (
          <g key={d.co.id}>
            <rect x={x} y={y} width={barW} height={h} rx={3} fill={d.co.color}/>
            <text x={x + barW / 2} y={y - 4} textAnchor="middle" fontSize="9" fontFamily="monospace" fill="var(--text)">
              {d.total >= 1000000 ? (d.total / 1000000).toFixed(1) + 'M' : (d.total / 1000).toFixed(0) + 'k'}
            </text>
            <text x={x + barW / 2} y={H - P + 12} textAnchor="middle" fontSize="10" fill="var(--text-mute)">{d.co.code}</text>
          </g>
        );
      })}
    </svg>
  );
};

const StackedBarChart = ({ data }) => {
  const W = 720, H = 200, P = 30, rowH = 24, gap = 6;
  const maxTotal = Math.max(...data.map(d => d.green + d.amber + d.red)) || 1;
  return (
    <svg viewBox={`0 0 ${W} ${data.length * (rowH + gap) + 30}`} style={{ width: '100%' }}>
      {data.map((d, i) => {
        const total = d.green + d.amber + d.red;
        if (total === 0) return null;
        const y = i * (rowH + gap) + 10;
        const xBase = 110;
        const wAvail = W - xBase - 20;
        const wG = (d.green / maxTotal) * wAvail;
        const wA = (d.amber / maxTotal) * wAvail;
        const wR = (d.red / maxTotal) * wAvail;
        return (
          <g key={d.co.id}>
            <text x={100} y={y + rowH / 2 + 4} textAnchor="end" fontSize="11" fill="var(--text)">{d.co.name}</text>
            <rect x={xBase}              y={y} width={wG} height={rowH} fill="var(--green)" rx={3}/>
            <rect x={xBase + wG}         y={y} width={wA} height={rowH} fill="var(--amber)"/>
            <rect x={xBase + wG + wA}    y={y} width={wR} height={rowH} fill="var(--red)" rx={3}/>
            <text x={xBase + wG + wA + wR + 8} y={y + rowH / 2 + 4} fontSize="11" fontFamily="monospace" fill="var(--text-mute)">{total}</text>
          </g>
        );
      })}
    </svg>
  );
};

const FunnelChart = ({ stages }) => {
  const max = Math.max(...stages.map(s => s.count)) || 1;
  const W = 380, rowH = 50, gap = 4;
  return (
    <svg viewBox={`0 0 ${W} ${stages.length * (rowH + gap)}`} style={{ width: '100%' }}>
      {stages.map((s, i) => {
        const w = Math.max((s.count / max) * (W - 130), 60);
        const x = (W - w) / 2;
        const y = i * (rowH + gap);
        return (
          <g key={s.stage}>
            <rect x={x} y={y} width={w} height={rowH} fill={s.color} rx={4} opacity={0.92}/>
            <text x={W / 2} y={y + rowH / 2 - 2} textAnchor="middle" fontSize="11" fontWeight="600" fill="white">{s.stage}</text>
            <text x={W / 2} y={y + rowH / 2 + 14} textAnchor="middle" fontSize="13" fontWeight="700" fill="white" fontFamily="monospace">{s.count}</text>
          </g>
        );
      })}
    </svg>
  );
};

const DonutChart = ({ segments, total }) => {
  const size = 140, stroke = 24, r = (size - stroke) / 2;
  const C = 2 * Math.PI * r;
  let offset = 0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flexShrink: 0 }}>
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={stroke}/>
      {segments.map((seg, i) => {
        const len = (seg.count / total) * C;
        const dasharray = `${len} ${C}`;
        const dashoffset = -offset;
        const node = (
          <circle key={seg.priority || i}
            cx={size / 2} cy={size / 2} r={r}
            fill="none" stroke={seg.color} strokeWidth={stroke}
            strokeDasharray={dasharray} strokeDashoffset={dashoffset}
            transform={`rotate(-90 ${size / 2} ${size / 2})`}
          />
        );
        offset += len;
        return node;
      })}
      <text x={size / 2} y={size / 2 + 2} textAnchor="middle" fontSize="22" fontWeight="700" fill="var(--ink)" fontFamily="monospace">{total}</text>
      <text x={size / 2} y={size / 2 + 18} textAnchor="middle" fontSize="10" fill="var(--text-mute)">tickets</text>
    </svg>
  );
};

const HorizontalBars = ({ items, valueKey, unit }) => {
  const max = Math.max(...items.map(i => i[valueKey])) || 1;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {items.map(it => {
        const w = (it[valueKey] / max) * 100;
        return (
          <div key={it.stage}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 5 }}>
              <span style={{ color: 'var(--ink)', fontWeight: 500 }}>{it.stage}</span>
              <span className="text-mono text-mute">{it[valueKey]}{unit ? ` ${unit}` : ''}</span>
            </div>
            <div style={{ height: 10, background: 'var(--surface-3)', borderRadius: 5, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: w + '%', background: it.color, borderRadius: 5 }}></div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

const LineChart = ({ data }) => {
  const W = 720, H = 200, P = 30;
  const maxY = Math.max(...data.flatMap(d => [d.proposals, d.pos])) + 2;
  const xs = data.map((_, i) => P + i * ((W - P * 2) / (data.length - 1)));
  const yFor = (v) => H - P - (v / maxY) * (H - P * 2);
  const propLine = data.map((d, i) => `${xs[i]},${yFor(d.proposals)}`).join(' ');
  const posLine  = data.map((d, i) => `${xs[i]},${yFor(d.pos)}`).join(' ');
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%' }}>
      {[0, 0.25, 0.5, 0.75, 1].map(t => (
        <line key={t} x1={P} x2={W - P} y1={P + (1 - t) * (H - P * 2)} y2={P + (1 - t) * (H - P * 2)} stroke="var(--line-2)" strokeDasharray={t === 0 ? '0' : '2 3'}/>
      ))}
      <polyline points={propLine} fill="none" stroke="var(--accent)" strokeWidth="2.5"/>
      <polyline points={posLine}  fill="none" stroke="var(--ink)"    strokeWidth="2.5"/>
      {data.map((d, i) => (
        <g key={i}>
          <circle cx={xs[i]} cy={yFor(d.proposals)} r="3.5" fill="var(--accent)"/>
          <circle cx={xs[i]} cy={yFor(d.pos)}       r="3.5" fill="var(--ink)"/>
          <text x={xs[i]} y={H - P + 14} textAnchor="middle" fontSize="10" fill="var(--text-mute)">{d.m}</text>
        </g>
      ))}
    </svg>
  );
};

Object.assign(window, { ReportsPage });
