// Admin → KPIs & Targets
// - Define / edit / delete company KPIs (moved here from the Company KPIs page)
// - Enter per-designer MONTHLY targets for each KPI, per financial year
// - Lock any month so only Admin / General Manager / Store Manager can amend it
// - Every change is written to an immutable audit trail
function KPIAdmin({ kpis, kpiTargets, kpiLocks, kpiAudit, reps, showrooms, currentUser, onSaveKpiDef, onDeleteKpiDef, onSetTarget, onToggleLock }) {
  const canEdit = ['admin', 'leadership', 'manager'].includes(currentUser.role);
  const [editing, setEditing] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const [selKpi, setSelKpi] = React.useState((kpis[0] || {}).id || '');
  const [fyStart, setFyStart] = React.useState(2025);
  const [cells, setCells] = React.useState({});

  const fyMonths = (startYear) => {
    const labels = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    return Array.from({ length: 12 }).map((_, i) => {
      const monthIndex = (6 + i) % 12;
      const year = i < 6 ? startYear : startYear + 1;
      const q = Math.floor(i / 3) + 1;
      return { key: `${year}-${String(monthIndex + 1).padStart(2, '0')}`, label: `${labels[i]} ${String(year).slice(2)}`, q };
    });
  };
  const fyLabel = (y) => `FY${String(y + 1).slice(2)} (Jul ${String(y).slice(2)} – Jun ${String(y + 1).slice(2)})`;
  const fyOptions = Array.from({ length: 6 }).map((_, i) => 2025 + i);
  const months = fyMonths(fyStart);

  React.useEffect(() => { if (!kpis.find(k => k.id === selKpi) && kpis[0]) setSelKpi(kpis[0].id); }, [kpis]);

  const kpi = kpis.find(k => k.id === selKpi);
  const unit = (window.KPI_UNITS || {})[kpi && kpi.unit] || { fmt: (v) => v, prefix: '' };
  const tgt = (kpiTargets && kpiTargets[selKpi]) || {};
  const locks = (kpiLocks && kpiLocks[selKpi]) || {};

  // Seed local editable cells whenever the KPI, FY, or stored targets change
  React.useEffect(() => {
    const c = {};
    (reps || []).forEach(r => months.forEach(m => {
      const v = (tgt[r.id] || {})[m.key];
      c[r.id + '|' + m.key] = (v == null || v === '') ? '' : String(v);
    }));
    setCells(c);
  }, [selKpi, fyStart, kpiTargets]);

  const commit = (rid, mk) => {
    const raw = cells[rid + '|' + mk];
    const num = (raw === '' || raw == null) ? '' : (parseFloat(String(raw).replace(/[^\d.]/g, '')) || 0);
    const prev = (tgt[rid] || {})[mk];
    const prevNorm = (prev == null || prev === '') ? '' : Number(prev);
    if (num !== prevNorm) onSetTarget(selKpi, rid, mk, num);
  };

  const allLocked = months.every(m => locks[m.key]);
  const toggleAll = () => months.forEach(m => { if (allLocked ? locks[m.key] : !locks[m.key]) onToggleLock(selKpi, m.key); });

  const auditRows = (kpiAudit || []).filter(a => a.kpiId === selKpi).slice(0, 40);
  const totalForMonth = (mk) => (reps || []).reduce((s, r) => s + (Number((tgt[r.id] || {})[mk]) || 0), 0);

  return (
    <div>
      {/* KPI definitions */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-hd">
          <div>
            <div className="card-title">KPI definitions</div>
            <div className="card-sub">Create the metrics your business tracks · they appear on the Company KPIs reporting page</div>
          </div>
          {canEdit && <button className="btn sm primary" onClick={() => { setEditing(null); setAdding(true); }}><Icon name="plus" size={12}/> New KPI</button>}
        </div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>KPI</th><th>Measured in</th><th>Source</th><th>Period</th>{canEdit && <th></th>}</tr></thead>
            <tbody>
              {kpis.map(k => {
                const u = (window.KPI_UNITS || {})[k.unit] || { label: k.unit };
                const isAuto = k.source && k.source !== 'manual';
                return (
                  <tr key={k.id} className={k.id === selKpi ? 'selected' : ''} style={{ cursor: 'pointer' }} onClick={() => setSelKpi(k.id)}>
                    <td style={{ fontWeight: 500 }}>{k.name}</td>
                    <td style={{ color: 'var(--ink-2)' }}>{u.label}</td>
                    <td><span className="pill" style={{ fontSize: 10, background: isAuto ? 'var(--info-soft)' : 'var(--surface-3)', color: isAuto ? 'oklch(0.4 0.09 240)' : 'var(--ink-3)' }}>{isAuto ? 'Auto' : 'Manual'}</span></td>
                    <td style={{ color: 'var(--ink-2)' }}>{k.targetPeriod || 'month'}</td>
                    {canEdit && (
                      <td style={{ textAlign: 'right', whiteSpace: 'nowrap' }} onClick={(e) => e.stopPropagation()}>
                        <button className="btn sm" onClick={() => { setAdding(false); setEditing(k); }}><Icon name="edit" size={11}/></button>
                        <button className="btn sm" style={{ marginLeft: 4, color: 'var(--lost)' }} onClick={() => { if (confirm('Delete KPI "' + k.name + '"? Its targets stay in the audit trail.')) onDeleteKpiDef(k.id); }}><Icon name="close" size={11}/></button>
                      </td>
                    )}
                  </tr>
                );
              })}
              {kpis.length === 0 && <tr><td colSpan={canEdit ? 5 : 4} className="empty">No KPIs yet — add one to begin.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>

      {/* Monthly targets grid */}
      {kpi && (
        <div className="card" style={{ marginBottom: 18 }}>
          <div className="card-hd">
            <div>
              <div className="card-title">Monthly targets · {kpi.name}</div>
              <div className="card-sub">Per-designer target for each month · locked months can only be amended by Admin, General Manager or Store Manager</div>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <select className="sel" value={selKpi} onChange={(e) => setSelKpi(e.target.value)}>
                {kpis.map(k => <option key={k.id} value={k.id}>{k.name}</option>)}
              </select>
              <select className="sel" value={fyStart} onChange={(e) => setFyStart(Number(e.target.value))} style={{ minWidth: 190 }}>
                {fyOptions.map(y => <option key={y} value={y}>{fyLabel(y)}{y === 2025 ? ' · current' : ''}</option>)}
              </select>
              {canEdit && (
                <button className="btn sm" onClick={toggleAll} title="Lock or unlock the whole year">
                  <Icon name="lock" size={11}/> {allLocked ? 'Unlock all' : 'Lock all'}
                </button>
              )}
            </div>
          </div>

          <div className="tbl-wrap" style={{ overflowX: 'auto' }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ position: 'sticky', left: 0, background: 'var(--surface-2)', zIndex: 2, minWidth: 160 }}>Designer</th>
                  {months.map(m => {
                    const locked = !!locks[m.key];
                    return (
                      <th key={m.key} className="num-col" style={{ minWidth: 92, background: locked ? 'var(--surface-3)' : (m.q % 2 === 0 ? 'var(--surface-2)' : 'var(--surface-3)') }}>
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                          <span>{m.label}</span>
                          {canEdit ? (
                            <button onClick={() => onToggleLock(selKpi, m.key)} title={locked ? 'Locked — click to unlock' : 'Unlocked — click to lock'}
                              style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 9, fontWeight: 600, color: locked ? 'var(--lost)' : 'var(--ink-4)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                              <Icon name={locked ? 'lock' : 'lock'} size={9}/>{locked ? 'LOCKED' : 'open'}
                            </button>
                          ) : (locked && <span style={{ fontSize: 9, color: 'var(--lost)' }}>LOCKED</span>)}
                        </div>
                      </th>
                    );
                  })}
                  <th className="num-col" style={{ background: 'var(--ink)', color: 'white', minWidth: 100 }}>FY total</th>
                </tr>
              </thead>
              <tbody>
                {(reps || []).map(r => {
                  const fyTotal = months.reduce((s, m) => s + (Number((tgt[r.id] || {})[m.key]) || 0), 0);
                  return (
                    <tr key={r.id}>
                      <td style={{ position: 'sticky', left: 0, background: 'var(--surface)', zIndex: 1, fontWeight: 500 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Avatar name={r.name} sz="sm"/>{r.name}</div>
                      </td>
                      {months.map(m => {
                        const locked = !!locks[m.key];
                        const key = r.id + '|' + m.key;
                        return (
                          <td key={m.key} className="num-col" style={{ background: locked ? 'oklch(0.965 0.005 80)' : (m.q % 2 === 0 ? 'oklch(0.99 0.005 80)' : 'transparent') }}>
                            <input
                              type="text"
                              value={cells[key] != null ? cells[key] : ''}
                              disabled={locked || !canEdit}
                              onChange={(e) => setCells(c => ({ ...c, [key]: e.target.value }))}
                              onBlur={() => commit(r.id, m.key)}
                              placeholder={locked ? '🔒' : '0'}
                              style={{ width: 72, padding: '4px 6px', border: '1px solid transparent', borderRadius: 4, fontSize: 12, textAlign: 'right', background: 'transparent', fontFamily: 'inherit', color: locked ? 'var(--ink-3)' : 'var(--ink)', cursor: locked ? 'not-allowed' : 'text' }}
                              onFocus={(e) => { if (!locked && canEdit) { e.target.style.borderColor = 'var(--ink-3)'; e.target.style.background = 'white'; } }}
                              onBlurCapture={(e) => { e.target.style.borderColor = 'transparent'; e.target.style.background = 'transparent'; }}
                            />
                          </td>
                        );
                      })}
                      <td className="num-col" style={{ background: 'oklch(0.96 0.01 80)', fontWeight: 600 }}><span className="num">{fyTotal ? unit.fmt(fyTotal) : '—'}</span></td>
                    </tr>
                  );
                })}
                <tr style={{ background: 'var(--surface-2)', borderTop: '2px solid var(--border)' }}>
                  <td style={{ position: 'sticky', left: 0, background: 'var(--surface-2)', zIndex: 1, fontWeight: 600, fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Team total</td>
                  {months.map(m => <td key={m.key} className="num-col" style={{ fontSize: 11.5, color: 'var(--ink-2)' }}><span className="num">{totalForMonth(m.key) ? unit.fmt(totalForMonth(m.key)) : '—'}</span></td>)}
                  <td className="num-col" style={{ background: 'var(--ink)', color: 'white', fontWeight: 700 }}><span className="num">{unit.fmt((reps || []).reduce((s, r) => s + months.reduce((t, m) => t + (Number((tgt[r.id] || {})[m.key]) || 0), 0), 0))}</span></td>
                </tr>
              </tbody>
            </table>
          </div>
          <div style={{ padding: '10px 18px', borderTop: '1px solid var(--border)', fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="check" size={12} color="var(--won)"/> Changes save instantly and are recorded in the audit trail below. This KPI’s targets feed the Company KPIs reporting page.
          </div>
        </div>
      )}

      {/* Audit trail */}
      <div className="card">
        <div className="card-hd">
          <div>
            <div className="card-title">Audit trail{kpi ? ' · ' + kpi.name : ''}</div>
            <div className="card-sub">Immutable record of every target change, lock and unlock</div>
          </div>
        </div>
        {auditRows.length === 0 ? (
          <div className="empty">No changes recorded for this KPI yet.</div>
        ) : (
          <div className="activity-list" style={{ padding: '10px 18px' }}>
            {auditRows.map((a, i) => (
              <div className="activity-item" key={i} style={{ alignItems: 'flex-start' }}>
                <span className="activity-dot" style={{ background: a.action === 'lock' ? 'var(--lost)' : a.action === 'unlock' ? 'var(--warn)' : 'var(--info)' }}></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500 }}>
                    {a.action === 'lock' ? `Locked ${a.month}` : a.action === 'unlock' ? `Unlocked ${a.month}` : `${a.repName || 'Designer'} · ${a.month} target ${fmtAuditVal(a.prev, unit)} → ${fmtAuditVal(a.next, unit)}`}
                  </div>
                  <div className="activity-meta">by {a.by} · {a.tsLabel}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {(editing || adding) && window.KPIEditor && (
        <KPIEditor
          kpi={editing}
          reps={reps || []}
          onClose={() => { setEditing(null); setAdding(false); }}
          onSave={(k) => { onSaveKpiDef(k); setEditing(null); setAdding(false); if (!k.id) setTimeout(() => {}, 0); }}
        />
      )}
    </div>
  );
}

function fmtAuditVal(v, unit) {
  if (v == null || v === '') return '—';
  return unit && unit.fmt ? unit.fmt(v) : String(v);
}

window.KPIAdmin = KPIAdmin;
