/* ============================================================
   Reja (target) — kompaniya / brend / distributor kesimida oylik reja.
   Reja platformada (DB) kiritiladi (faqat super admin), fakt — sell-out
   (Google Sheets) dan jonli olinadi. /api/targets/overview.
   ddShort/ddFull/ddPct/ddStatus — distributors.jsx'dan (umumiy scope).
   ============================================================ */

const TGT_MONTHS = ['Yanvar', 'Fevral', 'Mart', 'Aprel', 'May', 'Iyun', 'Iyul', 'Avgust', 'Sentyabr', 'Oktyabr', 'Noyabr', 'Dekabr'];

function TgtRow({ row, canEdit, onSave }) {
  const [val, setVal] = useState(row.amount ? String(Math.round(row.amount)) : '');
  useEffect(() => { setVal(row.amount ? String(Math.round(row.amount)) : ''); }, [row.amount]);
  const st = ddStatus(row.pct);
  const commit = () => {
    const n = Math.max(0, Math.round(Number(val) || 0));
    if (n !== Math.round(row.amount || 0)) onSave(row, n);
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderTop: '1px solid var(--border)' }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={row.name}>{row.name}</div>
        {row.region && <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>{row.region}</div>}
      </div>
      <div style={{ width: 150, flex: 'none' }}>
        {canEdit ? (
          <input className="input tnum" type="number" min="0" value={val} placeholder="Reja…"
            onChange={(e) => setVal(e.target.value)} onBlur={commit}
            onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }}
            style={{ height: 32, textAlign: 'right', width: '100%' }} />
        ) : (
          <div className="tnum" style={{ textAlign: 'right', fontWeight: 700 }}>{row.amount ? ddFull(row.amount) : '—'}</div>
        )}
      </div>
      <div className="tnum" style={{ width: 110, flex: 'none', textAlign: 'right', fontWeight: 700, color: 'var(--ink-2)' }} title={ddFull(row.fakt) + " so'm"}>{ddShort(row.fakt)}</div>
      <div style={{ width: 64, flex: 'none', textAlign: 'right' }}>
        <span className="tnum" style={{ display: 'inline-block', minWidth: 48, textAlign: 'center', padding: '2px 8px', borderRadius: 999, fontWeight: 800, fontSize: 11.5, background: st.tint, color: st.ink }}>{ddPct(row.pct)}</span>
      </div>
    </div>
  );
}

function TgtSection({ title, sub, rows, canEdit, onSave }) {
  const totReja = rows.reduce((s, r) => s + (r.amount || 0), 0);
  const totFakt = rows.reduce((s, r) => s + (r.fakt || 0), 0);
  const pct = totReja > 0 ? totFakt / totReja : null;
  const st = ddStatus(pct);
  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', marginBottom: 16, overflow: 'hidden' }}>
      <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ fontWeight: 800, fontSize: 14 }}>{title}</div>
        {sub && <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{sub}</div>}
        <div style={{ flex: 1 }} />
        {rows.length > 1 && (
          <span style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>
            reja <b className="tnum" style={{ color: 'var(--ink-2)' }}>{ddShort(totReja)}</b> · fakt <b className="tnum" style={{ color: 'var(--ink-2)' }}>{ddShort(totFakt)}</b> ·
            <span className="tnum" style={{ marginLeft: 6, padding: '1px 7px', borderRadius: 999, fontWeight: 800, background: st.tint, color: st.ink }}>{ddPct(pct)}</span>
          </span>
        )}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px', background: 'var(--bg-2)', fontSize: 10.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em', fontWeight: 700 }}>
        <div style={{ flex: 1 }}>Nomi</div>
        <div style={{ width: 150, flex: 'none', textAlign: 'right' }}>Reja (so'm)</div>
        <div style={{ width: 110, flex: 'none', textAlign: 'right' }}>Fakt</div>
        <div style={{ width: 64, flex: 'none', textAlign: 'right' }}>Bajarish</div>
      </div>
      {rows.length === 0
        ? <div style={{ padding: 16, color: 'var(--ink-4)', fontSize: 12.5 }}>Ma'lumot yo'q</div>
        : rows.map((r, i) => <TgtRow key={r.scope + (r.refId || '') + i} row={r} canEdit={canEdit} onSave={onSave} />)}
    </div>
  );
}

function Targets({ user, showToast }) {
  const now = new Date();
  const [year, setYear] = useState(now.getFullYear());
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);

  const load = useCallback(async () => {
    setLoading(true);
    try { setData(await API.targetsOverview(year, month)); setErr(null); }
    catch (ex) { setErr((ex && ex.message) || 'Yuklashda xatolik'); }
    finally { setLoading(false); }
  }, [year, month]);
  useEffect(() => { load(); }, [load]);

  const canEdit = !!(data && data.canEdit);

  const saveRow = useCallback(async (row, amount) => {
    try {
      const { target } = await API.saveTarget({ scope: row.scope, refId: row.refId || '', year, month, amount });
      setData((d) => {
        if (!d) return d;
        const upd = (r) => (r.scope === row.scope && (r.refId || '') === (row.refId || ''))
          ? { ...r, id: target.id, amount, pct: amount > 0 ? (r.fakt || 0) / amount : null } : r;
        return {
          ...d,
          company: upd(d.company),
          brands: (d.brands || []).map(upd),
          distributors: (d.distributors || []).map(upd),
        };
      });
      showToast('Reja saqlandi');
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); }
  }, [year, month, showToast]);

  const years = [now.getFullYear() - 1, now.getFullYear(), now.getFullYear() + 1];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      <div className="board-toolbar" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 22px 12px', flexWrap: 'wrap' }}>
        <div>
          <h2 style={{ fontSize: 18, fontWeight: 800, letterSpacing: '-.02em', margin: 0 }}>Reja</h2>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>
            Oylik reja ↔ sell-out fakt{canEdit ? '' : ' · faqat ko‘rish'}
          </div>
        </div>
        <div style={{ flex: 1 }} />
        <select className="input" value={month} onChange={(e) => setMonth(parseInt(e.target.value, 10))} style={{ height: 36, width: 130 }}>
          {TGT_MONTHS.map((m, i) => <option key={i} value={i + 1}>{m}</option>)}
        </select>
        <select className="input" value={year} onChange={(e) => setYear(parseInt(e.target.value, 10))} style={{ height: 36, width: 100 }}>
          {years.map((y) => <option key={y} value={y}>{y}</option>)}
        </select>
        <button className="btn btn--ghost" style={{ height: 36 }} onClick={load} title="Yangilash"><Icon name="grid" size={16} /> Yangilash</button>
      </div>

      <div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '4px 22px 24px' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>
        ) : err ? (
          <Empty icon="alert" text={err} />
        ) : data ? (
          <>
            {!data.faktAvailable && (
              <div style={{ marginBottom: 14, padding: '9px 12px', borderRadius: 10, background: 'rgba(227,162,59,.10)', border: '1px solid rgba(227,162,59,.4)', fontSize: 12, color: 'var(--ink-2)' }}>
                {data.note || (TGT_MONTHS[month - 1] + ' uchun sell-out fakt hozircha mavjud emas — reja kiritsangiz bo‘ladi, fakt keyin chiqadi.')}
              </div>
            )}
            <TgtSection title="Kompaniya" sub="umumiy oylik reja" rows={[data.company]} canEdit={canEdit} onSave={saveRow} />
            <TgtSection title="Brendlar" sub="Brendlar kesimida" rows={data.brands || []} canEdit={canEdit} onSave={saveRow} />
            <TgtSection title="Distributorlar" sub={(data.distributors || []).length + ' ta'} rows={data.distributors || []} canEdit={canEdit} onSave={saveRow} />
            {!data.distFaktAvailable && (data.distributors || []).length > 0 && (
              <div style={{ fontSize: 11.5, color: 'var(--ink-4)', padding: '0 2px' }}>
                Distributor fakti uchun "Distributorlar" varag'ini ulang — fakt avtomatik tortiladi.
              </div>
            )}
          </>
        ) : null}
      </div>
    </div>
  );
}
