// Targets — leadership upload + per-designer monthly/quarterly tracking
// Stores per-designer per-month target $ in localStorage
//
// Data shape (window.SALES_DATA.TARGETS or kub_targets_v1):
// { 'r_ally': { '2026-07': 40000, '2026-08': 45000, ... }, 'r_deena': {...} }

const FY_MONTHS = [
  // Australian FY: Jul 2025 → Jun 2026 (current FY)
  { key: '2025-07', label: 'Jul 25', q: 1 },
  { key: '2025-08', label: 'Aug 25', q: 1 },
  { key: '2025-09', label: 'Sep 25', q: 1 },
  { key: '2025-10', label: 'Oct 25', q: 2 },
  { key: '2025-11', label: 'Nov 25', q: 2 },
  { key: '2025-12', label: 'Dec 25', q: 2 },
  { key: '2026-01', label: 'Jan 26', q: 3 },
  { key: '2026-02', label: 'Feb 26', q: 3 },
  { key: '2026-03', label: 'Mar 26', q: 3 },
  { key: '2026-04', label: 'Apr 26', q: 4 },
  { key: '2026-05', label: 'May 26', q: 4 },
  { key: '2026-06', label: 'Jun 26', q: 4 },
];

function TargetsAdmin({ reps, currentUser, onSave, targets }) {
  const [draft, setDraft] = React.useState(targets || {});
  const [fyStart, setFyStart] = React.useState(2025); // FY start year (Jul) — 2025 = FY26 (current)
  const [bulkMode, setBulkMode] = React.useState(false);
  const [bulkValues, setBulkValues] = React.useState({}); // rep_id -> annual $ to split

  // Build the 12 months for any FY (Jul → Jun)
  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;            // Jul = index 6
      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 = (startYear) => `FY${String(startYear + 1).slice(2)} (Jul ${String(startYear).slice(2)} – Jun ${String(startYear + 1).slice(2)})`;
  const fyOptions = Array.from({ length: 6 }).map((_, i) => 2025 + i); // current + next 5
  const months = fyMonths(fyStart);

  const updateCell = (repId, monthKey, value) => {
    const cleaned = parseFloat(String(value).replace(/[^\d.]/g, '')) || 0;
    setDraft(prev => ({
      ...prev,
      [repId]: { ...(prev[repId] || {}), [monthKey]: cleaned },
    }));
  };

  const applyBulk = (repId) => {
    const annual = parseFloat(String(bulkValues[repId] || '').replace(/[^\d.]/g, '')) || 0;
    if (annual <= 0) return;
    const monthly = Math.round(annual / 12);
    setDraft(prev => ({
      ...prev,
      [repId]: months.reduce((acc, m) => ({ ...acc, [m.key]: monthly }), prev[repId] || {}),
    }));
    setBulkValues(prev => ({ ...prev, [repId]: '' }));
  };

  const copyFromPrevMonth = (repId) => {
    const repTargets = draft[repId] || {};
    const filled = { ...repTargets };
    let lastKnown = 0;
    for (const m of months) {
      if (filled[m.key] > 0) lastKnown = filled[m.key];
      else if (lastKnown > 0) filled[m.key] = lastKnown;
    }
    setDraft(prev => ({ ...prev, [repId]: filled }));
  };

  // CSV bulk upload
  const fileInputRef = React.useRef(null);
  const handleCSVUpload = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (evt) => {
      const text = evt.target.result;
      try {
        const lines = text.trim().split(/\r?\n/);
        const header = lines[0].split(',').map(s => s.trim());
        // Expected: Designer, Jul 25, Aug 25, ...
        const monthCols = header.slice(1).map(h => {
          const m = months.find(mo => mo.label.toLowerCase() === h.toLowerCase());
          return m?.key || null;
        });
        const newDraft = { ...draft };
        let imported = 0;
        for (let i = 1; i < lines.length; i++) {
          const cells = lines[i].split(',').map(s => s.trim());
          const designerName = cells[0];
          const rep = reps.find(r => r.name.toLowerCase() === designerName.toLowerCase());
          if (!rep) continue;
          if (!newDraft[rep.id]) newDraft[rep.id] = {};
          for (let j = 0; j < monthCols.length; j++) {
            if (!monthCols[j]) continue;
            const val = parseFloat(cells[j + 1]?.replace(/[$,]/g, '')) || 0;
            newDraft[rep.id][monthCols[j]] = val;
          }
          imported++;
        }
        setDraft(newDraft);
        alert(`Imported targets for ${imported} designer${imported !== 1 ? 's' : ''}.`);
      } catch (err) {
        alert('Could not parse CSV. Expected format:\nDesigner, Jul 25, Aug 25, Sep 25, ...');
      }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  const downloadTemplate = () => {
    const headers = ['Designer', ...months.map(m => m.label)];
    const rows = reps.map(r => [r.name, ...months.map(() => 0)]);
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `targets-template-FY${String(fyStart + 1).slice(2)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const totals = months.reduce((acc, m) => {
    acc[m.key] = reps.reduce((s, r) => s + ((draft[r.id] || {})[m.key] || 0), 0);
    return acc;
  }, {});
  const grandAnnual = Object.values(totals).reduce((a, b) => a + b, 0);

  return (
    <div>
      <div className="card" style={{ marginBottom: 16, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14, background: 'var(--info-soft)', border: '1px solid oklch(0.85 0.04 240)' }}>
        <div style={{
          width: 32, height: 32, borderRadius: 16,
          background: 'var(--info)', color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name="target" size={16} color="white"/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'oklch(0.3 0.1 240)', marginBottom: 2 }}>
            Set yearly targets for each designer
          </div>
          <div style={{ fontSize: 12, color: 'oklch(0.35 0.08 240)' }}>
            Enter monthly targets per designer. They'll show up on each designer's Forecast page with monthly, quarterly, and FY progress. Upload a CSV for fast bulk entry, or type values directly.
          </div>
        </div>
        <button className="btn sm" onClick={() => fileInputRef.current?.click()}>
          <Icon name="download" size={12} style={{ transform: 'rotate(180deg)' }}/> Upload CSV
        </button>
        <button className="btn sm" onClick={downloadTemplate}>
          <Icon name="download" size={12}/> Template
        </button>
        <input ref={fileInputRef} type="file" accept=".csv" onChange={handleCSVUpload} style={{ display: 'none' }}/>
      </div>

      <div className="card">
        <div className="card-hd">
          <div>
            <div className="card-title">Designer monthly targets</div>
            <div className="card-sub">Team total: <span className="num" style={{ color: 'var(--ink)', fontWeight: 600 }}>{fmt.money(grandAnnual, true)}</span> across {fyLabel(fyStart).split(' ')[0]}</div>
          </div>
          <select className="sel" value={fyStart} onChange={(e) => setFyStart(Number(e.target.value))} style={{ fontWeight: 500, minWidth: 200 }}>
            {fyOptions.map(y => <option key={y} value={y}>{fyLabel(y)}{y === 2025 ? ' · current' : ''}</option>)}
          </select>
        </div>

        <div style={{ padding: '10px 18px', display: 'flex', gap: 8, alignItems: 'center', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--border)' }}>
          <button className={`filter-chip ${bulkMode ? 'active' : ''}`} onClick={() => setBulkMode(!bulkMode)}>
            <Icon name="sliders" size={11}/> {bulkMode ? 'Hide annual splitter' : 'Show annual splitter'}
          </button>
          <span style={{ marginLeft: 8 }}>Tip: type one month's value and press the copy-down arrow to fill the rest →</span>
        </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>
                {bulkMode && <th style={{ background: 'var(--accent-soft)' }}>Annual $ (split /12)</th>}
                {months.map(m => (
                  <th key={m.key} className="num-col" style={{ minWidth: 90, background: m.q % 2 === 0 ? 'var(--surface-2)' : 'var(--surface-3)' }}>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>Q{m.q}</div>
                    {m.label}
                  </th>
                ))}
                <th className="num-col" style={{ background: 'var(--ink)', color: 'white', minWidth: 110 }}>FY Total</th>
              </tr>
            </thead>
            <tbody>
              {reps.map(r => {
                const repTargets = draft[r.id] || {};
                const annualTotal = months.reduce((s, m) => s + (repTargets[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"/>
                        <div>
                          <div>{r.name}</div>
                          <button onClick={() => copyFromPrevMonth(r.id)} style={{ fontSize: 10, color: 'var(--ink-3)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                            ↳ fill empty from prev
                          </button>
                        </div>
                      </div>
                    </td>
                    {bulkMode && (
                      <td style={{ background: 'oklch(0.97 0.02 25)' }}>
                        <div style={{ display: 'flex', gap: 4 }}>
                          <input
                            type="text"
                            placeholder="e.g. 480000"
                            value={bulkValues[r.id] || ''}
                            onChange={(e) => setBulkValues(prev => ({ ...prev, [r.id]: e.target.value }))}
                            style={{ width: 100, padding: '4px 6px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12 }}
                          />
                          <button className="btn sm" style={{ padding: '3px 8px' }} onClick={() => applyBulk(r.id)}>Split</button>
                        </div>
                      </td>
                    )}
                    {months.map(m => (
                      <td key={m.key} className="num-col" style={{ background: m.q % 2 === 0 ? 'oklch(0.99 0.005 80)' : 'transparent' }}>
                        <input
                          type="text"
                          value={repTargets[m.key] || ''}
                          onChange={(e) => updateCell(r.id, m.key, e.target.value)}
                          placeholder="0"
                          style={{ width: 70, padding: '4px 6px', border: '1px solid transparent', borderRadius: 4, fontSize: 12, textAlign: 'right', background: 'transparent', fontFamily: 'inherit' }}
                          onFocus={(e) => { e.target.style.borderColor = 'var(--ink-3)'; e.target.style.background = 'white'; }}
                          onBlur={(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">{fmt.money(annualTotal, true)}</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: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Team total</td>
                {bulkMode && <td></td>}
                {months.map(m => (
                  <td key={m.key} className="num-col" style={{ background: 'var(--surface-2)', fontWeight: 500, fontSize: 11.5, color: 'var(--ink-2)' }}>
                    <span className="num">{totals[m.key] > 0 ? fmt.money(totals[m.key], true) : '—'}</span>
                  </td>
                ))}
                <td className="num-col" style={{ background: 'var(--ink)', color: 'white', fontWeight: 700 }}>
                  <span className="num">{fmt.money(grandAnnual, true)}</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div style={{ padding: '14px 18px', borderTop: '1px solid var(--border)', display: 'flex', gap: 8, background: 'var(--surface-2)' }}>
          <button className="btn" onClick={() => setDraft(targets || {})}>Revert changes</button>
          <button className="btn primary" style={{ marginLeft: 'auto' }} onClick={() => onSave(draft)}>
            <Icon name="check" size={12}/> Save targets
          </button>
        </div>
      </div>
    </div>
  );
}

// Helper: compute progress for a designer (or all) against targets
function computeTargetProgress(deals, targets, repId, periodKeys) {
  // periodKeys: array of 'YYYY-MM' months
  let targetTotal = 0;
  for (const key of periodKeys) {
    if (repId) targetTotal += (targets[repId] || {})[key] || 0;
    else {
      // Sum all reps
      for (const rep of Object.keys(targets)) targetTotal += (targets[rep] || {})[key] || 0;
    }
  }
  // Sum sold value for that period — based on when the deal was won (forecastDepositMonth or lastActivity)
  let achieved = 0;
  for (const d of deals) {
    if (d.stage !== 'sold') continue;
    if (repId && d.rep !== repId) continue;
    // Use forecastDepositMonth as the recognised "won month" first, fall back to lastActivity then created
    const closeDate = d.forecastDepositMonth || d.lastActivity || d.created;
    if (!closeDate) continue;
    const monthKey = closeDate.slice(0, 7);
    if (periodKeys.includes(monthKey)) achieved += d.value;
  }
  return { targetTotal, achieved, pct: targetTotal > 0 ? achieved / targetTotal : 0 };
}

window.TargetsAdmin = TargetsAdmin;
window.FY_MONTHS = FY_MONTHS;
window.computeTargetProgress = computeTargetProgress;
