/* ============================================================
   Distributorlar — distributor kesimida sell-out, sklad qoldig'i,
   debitorka (qarz) va AKB. Manba: maxfiy Google Sheets (token serverda).
   /api/distributor-dashboard — hudud bo'yicha kesilgan (regional menejer —
   faqat o'z viloyat(lar)i). Keyinchalik API'ga ulanadi (faqat backend o'zgaradi).
   ============================================================ */

const DD_REFRESH_MS = 5 * 60 * 1000; // 5 daqiqa

function ddShort(v) {
  const n = Number(v) || 0;
  const a = Math.abs(n);
  if (a >= 1e9) return (n / 1e9).toFixed(2).replace(/\.?0+$/, '') + ' mlrd';
  if (a >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + ' mln';
  if (a >= 1e3) return Math.round(n / 1e3) + ' ming';
  return String(Math.round(n));
}
const ddFull = (v) => Number(v || 0).toLocaleString('ru-RU').replace(/,/g, ' ');
const ddPct = (v) => (v == null ? '—' : (Number(v) * 100).toFixed(0) + '%');

// Sell-out bajarilishiga qarab rang
function ddStatus(pct) {
  if (pct == null) return { ink: 'var(--ink-4)', tint: 'var(--bg-2)', border: 'var(--border)', dot: 'var(--ink-4)', label: '—' };
  if (pct >= 1) return { ink: '#1D8A6E', tint: 'rgba(61,190,156,.10)', border: 'rgba(61,190,156,.45)', dot: '#3DBE9C', label: 'Yaxshi' };
  if (pct >= 0.7) return { ink: '#A6651E', tint: 'rgba(227,162,59,.12)', border: 'rgba(227,162,59,.5)', dot: '#E3A23B', label: 'Yaqin' };
  return { ink: '#C2453A', tint: 'rgba(232,115,95,.10)', border: 'rgba(232,115,95,.45)', dot: '#E8735F', label: 'Past' };
}

function DdStat({ label, value, sub, accent }) {
  return (
    <div style={{ flex: '1 1 150px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '13px 16px', boxShadow: 'var(--sh-1)' }}>
      <div style={{ fontSize: 11.5, color: 'var(--ink-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.03em' }}>{label}</div>
      <div className="tnum" style={{ fontSize: 22, fontWeight: 800, marginTop: 3, color: accent || 'var(--ink)', lineHeight: 1.1 }}>{value}</div>
      {sub != null && <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

// Distributor profil — barcha ko'rsatkichlar bitta oynada
function DistributorProfile({ d, onClose }) {
  const st = ddStatus(d.pct);
  const row = (label, value, color) => (
    <div style={{ display: 'flex', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
      <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{label}</span>
      <div style={{ flex: 1 }} />
      <span className="tnum" style={{ fontSize: 14, fontWeight: 700, color: color || 'var(--ink)' }}>{value}</span>
    </div>
  );
  return (
    <Modal onClose={onClose} width={460}>
      <ModalHeader title={d.name} subtitle={d.region || 'Distributor'} onClose={onClose} />
      <div style={{ padding: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', borderRadius: 12, background: st.tint, border: '1px solid ' + st.border, marginBottom: 14 }}>
          <span className="dot" style={{ width: 10, height: 10, background: st.dot }} />
          <span style={{ fontWeight: 700, color: st.ink }}>Sell-out {ddPct(d.pct)}</span>
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>reja {ddShort(d.plan)} · fakt {ddShort(d.fakt)}</span>
        </div>
        {row('Sell-out reja', ddFull(d.plan) + " so'm")}
        {row('Sell-out fakt', ddFull(d.fakt) + " so'm", st.ink)}
        {row('Sklad qoldig‘i', ddFull(d.stock) + " so'm")}
        {row('Qarz (debitorka)', ddFull(d.debt) + " so'm", d.overLimit ? '#C2453A' : 'var(--ink)')}
        {d.limit > 0 && row('Kredit limiti', ddFull(d.limit) + " so'm")}
        {row('AKB (faol do‘konlar)', d.akb ? ddFull(d.akb) : '—')}
        {d.overLimit && (
          <div style={{ marginTop: 12, padding: '9px 12px', borderRadius: 10, background: 'rgba(232,115,95,.10)', color: '#C2453A', fontSize: 12.5, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="alert" size={15} /> Qarz kredit limitidan oshgan
          </div>
        )}
      </div>
    </Modal>
  );
}

function DistributorCard({ d, onOpen }) {
  const st = ddStatus(d.pct);
  return (
    <button onClick={() => onOpen(d)}
      style={{ textAlign: 'left', cursor: 'pointer', background: 'var(--surface)', border: '1px solid ' + st.border,
               borderRadius: 'var(--r-lg)', padding: '14px 15px', display: 'flex', flexDirection: 'column', gap: 10, boxShadow: 'var(--sh-1)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span className="dot" style={{ width: 9, height: 9, background: st.dot, flex: 'none' }} />
        <span style={{ fontWeight: 800, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 }} title={d.name}>{d.name}</span>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 10, fontWeight: 800, color: st.ink, background: st.tint, borderRadius: 999, padding: '2px 8px', flex: 'none' }}>{ddPct(d.pct)}</span>
      </div>
      {d.region && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: 'var(--ink-4)', marginTop: -4 }}>
          <Icon name="pin" size={12} /> {d.region}
        </div>
      )}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, borderTop: '1px solid var(--border)', paddingTop: 10 }}>
        <div>
          <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em' }}>Sell-out fakt</div>
          <div className="tnum" style={{ fontWeight: 700, fontSize: 13, color: st.ink }}>{ddShort(d.fakt)}</div>
        </div>
        <div>
          <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em' }}>Qoldiq</div>
          <div className="tnum" style={{ fontWeight: 700, fontSize: 13 }}>{ddShort(d.stock)}</div>
        </div>
        <div>
          <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em' }}>Qarz</div>
          <div className="tnum" style={{ fontWeight: 700, fontSize: 13, color: d.overLimit ? '#C2453A' : 'var(--ink)' }}>{ddShort(d.debt)}</div>
        </div>
        <div>
          <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.03em' }}>AKB</div>
          <div className="tnum" style={{ fontWeight: 700, fontSize: 13 }}>{d.akb ? ddFull(d.akb) : '—'}</div>
        </div>
      </div>
    </button>
  );
}

// Sheet hali ulanmagan — qanday shakllantirish kerakligini ko'rsatadigan yo'riqnoma
function DdSetupHint({ tab, reason }) {
  const cols = [
    ['Distributor', 'distributor nomi (majburiy)'],
    ['Viloyat', 'hudud bo‘yicha ajratish uchun'],
    ['Sell-out reja', 'oylik reja (so‘m)'],
    ['Sell-out fakt', 'oylik fakt (so‘m)'],
    ['Qoldiq', 'sklad qoldig‘i (so‘m)'],
    ['Qarz', 'debitorka (so‘m)'],
    ['Kredit limit', 'ixtiyoriy — oshsa qizil'],
    ['AKB', 'faol do‘konlar soni'],
  ];
  return (
    <div style={{ maxWidth: 640, margin: '20px auto', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 22, boxShadow: 'var(--sh-1)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
        <span style={{ color: '#A6651E', display: 'inline-flex' }}><Icon name="alert" size={18} /></span>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>Distributor varag'i hali ulanmagan</h3>
      </div>
      <p style={{ fontSize: 12.5, color: 'var(--ink-3)', margin: '0 0 14px' }}>
        Google Sheets'da <b>"{tab}"</b> nomli varaq oching va birinchi qatorga quyidagi sarlavhalarni yozing.
        Har keyingi qator — bitta distributor. Ustun tartibi muhim emas — tizim sarlavha nomi bo'yicha topadi.
      </p>
      <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r)', overflow: 'hidden' }}>
        {cols.map(([c, d], i) => (
          <div key={c} style={{ display: 'flex', gap: 10, padding: '9px 14px', borderTop: i ? '1px solid var(--border)' : 'none', fontSize: 12.5 }}>
            <span className="tnum" style={{ fontWeight: 700, minWidth: 130 }}>{c}</span>
            <span style={{ color: 'var(--ink-4)' }}>{d}</span>
          </div>
        ))}
      </div>
      <p style={{ fontSize: 11.5, color: 'var(--ink-4)', margin: '12px 0 0' }}>
        Varaq tayyor bo'lgach — bu sahifa avtomatik to'ladi. {reason ? '(' + reason + ')' : ''}
      </p>
    </div>
  );
}

function Distributors({ user, showToast }) {
  // Sahifa keshi — bo'limga qayta kirilganda oldingi ma'lumot darrov ko'rsatiladi.
  const ddCached = window.PageCache ? window.PageCache.get('distributors') : null;
  const [data, setData] = useState(ddCached || null);
  const [loading, setLoading] = useState(!ddCached);
  const [err, setErr] = useState(null);
  const [q, setQ] = useState('');
  const [sort, setSort] = useState('fakt'); // fakt | debt | stock | name | pct
  const [open, setOpen] = useState(null);

  // refresh — serverda majburiy yangilash (faqat "Yangilash" tugmasi);
  // silent — spinner ko'rsatmasdan (avto-yangilash).
  const load = useCallback(async (refresh, silent) => {
    if (!refresh && !silent) setLoading(true);
    try {
      const res = await API.distributorDashboard(refresh);
      setData(res); setErr(null);
      if (window.PageCache) window.PageCache.set('distributors', res);
    }
    catch (ex) { setErr((ex && ex.message) || 'Yuklashda xatolik'); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(false, !!ddCached); }, [load]); // kesh bor — spinnersiz fon yangilash
  useEffect(() => {
    // Avto-yangilash keshdan oladi — server fon isituvchisi keshni o'zi yangilab turadi.
    const t = setInterval(() => load(false, true), DD_REFRESH_MS);
    return () => clearInterval(t);
  }, [load]);

  const list = useMemo(() => {
    let arr = (data && data.distributors) || [];
    const needle = q.trim().toLowerCase();
    if (needle) arr = arr.filter((d) => (d.name || '').toLowerCase().includes(needle) || (d.region || '').toLowerCase().includes(needle));
    const cmp = {
      name: (a, b) => String(a.name).localeCompare(String(b.name), 'uz'),
      fakt: (a, b) => (b.fakt || 0) - (a.fakt || 0),
      debt: (a, b) => (b.debt || 0) - (a.debt || 0),
      stock: (a, b) => (b.stock || 0) - (a.stock || 0),
      pct: (a, b) => (b.pct || 0) - (a.pct || 0),
    };
    return [...arr].sort(cmp[sort] || cmp.fakt);
  }, [data, q, sort]);

  const totals = (data && data.totals) || null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
      {/* Toolbar */}
      <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 }}>Distributorlar</h2>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>
            Sell-out · sklad qoldig'i · debitorka{data && data.updatedAt ? ' · yangilandi ' + new Date(data.updatedAt).toLocaleTimeString('uz', { hour: '2-digit', minute: '2-digit' }) : ''}
          </div>
        </div>
        <div style={{ flex: 1 }} />
        {data && data.configured && (
          <input className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Qidirish…"
            style={{ height: 36, width: 180 }} />
        )}
        {data && data.configured && (
          <select className="input" value={sort} onChange={(e) => setSort(e.target.value)} style={{ height: 36, width: 150 }}>
            <option value="fakt">Sell-out fakt</option>
            <option value="debt">Qarz</option>
            <option value="stock">Qoldiq</option>
            <option value="pct">Bajarilish %</option>
            <option value="name">Nomi (A-Z)</option>
          </select>
        )}
        <button className="btn btn--ghost" style={{ height: 36 }} onClick={() => load(true)} title="Yangilash">
          <Icon name="refresh" 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.configured ? (
          <DdSetupHint tab={data.tab} reason={data.reason} />
        ) : (
          <>
            {totals && (
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
                <DdStat label="Distributorlar" value={totals.count} />
                <DdStat label="Sell-out fakt" value={ddShort(totals.fakt)} sub={'reja ' + ddShort(totals.plan) + ' · ' + ddPct(totals.pct)} accent={ddStatus(totals.pct).ink} />
                <DdStat label="Jami qoldiq" value={ddShort(totals.stock)} sub="sklad" />
                <DdStat label="Jami qarz" value={ddShort(totals.debt)} sub={totals.overLimit ? totals.overLimit + ' ta limitdan oshgan' : 'debitorka'} accent={totals.overLimit ? '#C2453A' : null} />
                <DdStat label="AKB" value={ddFull(totals.akb)} sub="faol do'konlar" />
              </div>
            )}

            {(data.warnings || []).length > 0 && (
              <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.warnings.map((w, i) => <div key={i}>• {w}</div>)}
              </div>
            )}

            {list.length === 0 ? (
              <Empty icon="user" text="Distributor topilmadi" />
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 12 }}>
                {list.map((d, i) => <DistributorCard key={i} d={d} onOpen={setOpen} />)}
              </div>
            )}
          </>
        )}
      </div>

      {open && <DistributorProfile d={open} onClose={() => setOpen(null)} />}
    </div>
  );
}
