/* ============================================================
   Sell-Out Dashboard (Iyul 2026+) — DB'dan jonli ma'lumot.
   Hisoblash: summa = units × unit_price,
              fakt_kor = units / units_per_carton.
   ============================================================ */

const SO_MONTHS = [
  { key: '2026-07', label: 'Iyul' },
  { key: '2026-08', label: 'Avgust' },
  { key: '2026-09', label: 'Sentyabr' },
  { key: '2026-10', label: 'Oktyabr' },
  { key: '2026-11', label: 'Noyabr' },
  { key: '2026-12', label: 'Dekabr' },
];

function soShort(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 soFull = (v) => Number(v || 0).toLocaleString('ru-RU').replace(/,/g, ' ');
const soPct  = (v) => ((Number(v || 0)) * 100).toFixed(1) + '%';
const soKor  = (v) => (Math.round((Number(v) || 0) * 10) / 10).toLocaleString('ru-RU').replace(/,/g, ' ');

function soStatus(pct) {
  if (pct >= 1)   return { tint: 'rgba(61,190,156,.15)', ink: '#1D8A6E', label: 'Bajarildi' };
  if (pct >= 0.7) return { tint: 'rgba(227,162,59,.16)', ink: '#A6651E', label: 'Yaqin' };
  return           { tint: 'rgba(232,115,95,.13)', ink: '#C2453A', label: 'Past' };
}

// ─── Kichik KPI karti ──────────────────────────────────────────────────────────
function SoKpi({ label, value, sub, color }) {
  return (
    <div style={{
      background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
      padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 5, minWidth: 0,
      boxShadow: 'var(--sh-1)',
    }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{label}</div>
      <div className="tnum" style={{ fontSize: 22, fontWeight: 700, lineHeight: 1.1, color: color || 'var(--ink)' }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{sub}</div>}
    </div>
  );
}

// ─── Region qatori (jadval) ───────────────────────────────────────────────────
function RegionRow({ reg, expanded, onToggle }) {
  const st = soStatus(reg.foiz);
  return (
    <>
      <tr
        onClick={onToggle}
        style={{ cursor: 'pointer', background: expanded ? 'var(--bg-2,rgba(0,0,0,.03))' : undefined }}
      >
        <td style={{ padding: '10px 14px', fontWeight: 700, fontSize: 13 }}>
          <span style={{ marginRight: 6, color: 'var(--ink-4)', fontSize: 11 }}>{expanded ? '▾' : '▸'}</span>
          {reg.name}
        </td>
        <td className="tnum" style={{ padding: '10px 12px', textAlign: 'right', fontSize: 13 }}>{soShort(reg.planSom)}</td>
        <td className="tnum" style={{ padding: '10px 12px', textAlign: 'right', fontSize: 13 }}>{soShort(reg.kunlikReja)}</td>
        <td className="tnum" style={{ padding: '10px 12px', textAlign: 'right', fontSize: 13, fontWeight: 700 }}>{soShort(reg.faktSom)}</td>
        <td style={{ padding: '10px 12px', textAlign: 'right' }}>
          <span style={{ background: st.tint, color: st.ink, padding: '3px 9px', borderRadius: 999, fontSize: 12, fontWeight: 700 }}>
            {soPct(reg.foiz)}
          </span>
        </td>
        <td className="tnum" style={{ padding: '10px 12px', textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{soKor(reg.planKor)} / {soKor(reg.faktKor)}</td>
      </tr>
      {expanded && reg.distributors.map((d) => (
        <DistributorRow key={d.id} dist={d} />
      ))}
    </>
  );
}

function DistributorRow({ dist }) {
  const st = soStatus(dist.foiz);
  return (
    <tr style={{ background: 'var(--bg,#fafafa)' }}>
      <td style={{ padding: '8px 14px 8px 32px', fontSize: 12.5, color: 'var(--ink-3)' }}>
        {dist.name}
      </td>
      <td className="tnum" style={{ padding: '8px 12px', textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{soShort(dist.planSom)}</td>
      <td style={{ padding: '8px 12px' }} />
      <td className="tnum" style={{ padding: '8px 12px', textAlign: 'right', fontSize: 12, fontWeight: 600 }}>{soShort(dist.faktSom)}</td>
      <td style={{ padding: '8px 12px', textAlign: 'right' }}>
        <span style={{ background: st.tint, color: st.ink, padding: '2px 8px', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
          {soPct(dist.foiz)}
        </span>
      </td>
      <td className="tnum" style={{ padding: '8px 12px', textAlign: 'right', fontSize: 11, color: 'var(--ink-4)' }}>
        {dist.skuPlans.filter(sp => sp.planKor > 0 || sp.faktKor > 0).map(sp => (
          <div key={sp.skuId} style={{ display: 'flex', justifyContent: 'space-between', gap: 8, minWidth: 160 }}>
            <span style={{ color: (DB.brandByTag(sp.brand) && DB.brandByTag(sp.brand).color) || 'var(--ink-3)', fontWeight: 600 }}>{sp.brand} {sp.skuName}</span>
            <span>{soKor(sp.faktKor)}/{sp.planKor} kor</span>
          </div>
        ))}
      </td>
    </tr>
  );
}

// ─── Kirish formasi (bugungi kun uchun) ───────────────────────────────────────
function EntryForm({ distributors, onSaved, showToast }) {
  const [distId, setDistId] = useState(distributors[0]?.id || '');
  const [date, setDate]   = useState(new Date().toISOString().slice(0, 10));
  const [vals, setVals]   = useState({});
  const [busy, setBusy]   = useState(false);

  const dist = distributors.find((d) => d.id === parseInt(distId));
  const plans = dist?.skuPlans || [];

  function setVal(skuId, v) {
    setVals((prev) => ({ ...prev, [skuId]: v }));
  }

  async function submit() {
    if (!dist) return;
    setBusy(true);
    try {
      for (const sp of plans) {
        const raw = vals[sp.skuId];
        const units = raw === '' || raw == null ? null : parseInt(raw);
        if (units !== null && isNaN(units)) continue;
        await API.soUpsert({ distributor_id: dist.id, sku_id: sp.skuId, sale_date: date, units });
      }
      showToast('Saqlandi');
      setVals({});
      if (onSaved) onSaved();
    } catch (e) {
      showToast(e.message || 'Saqlashda xatolik');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: 20, boxShadow: 'var(--sh-1)' }}>
      <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 16 }}>Kunlik kiritish</div>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: '1 1 200px' }}>
          <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)' }}>DISTRIBUTOR</label>
          <select className="select" value={distId} onChange={(e) => { setDistId(e.target.value); setVals({}); }} style={{ height: 38 }}>
            {distributors.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: '0 0 160px' }}>
          <label style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)' }}>SANA</label>
          <input className="input" type="date" value={date} onChange={(e) => setDate(e.target.value)} style={{ height: 38 }} />
        </div>
      </div>

      {plans.length === 0 ? (
        <div style={{ color: 'var(--ink-4)', fontSize: 13 }}>SKU rejalari topilmadi.</div>
      ) : (
        <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 16 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--border)' }}>
              <th style={{ textAlign: 'left', padding: '6px 0', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)', width: '30%' }}>SKU</th>
              <th style={{ textAlign: 'center', padding: '6px 8px', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)' }}>Birlik</th>
              <th style={{ textAlign: 'right', padding: '6px 8px', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)' }}>Plan (kor)</th>
              <th style={{ textAlign: 'right', padding: '6px 0', fontSize: 11.5, fontWeight: 600, color: 'var(--ink-4)', width: 110 }}>Kiritish</th>
            </tr>
          </thead>
          <tbody>
            {plans.map((sp) => (
              <tr key={sp.skuId} style={{ borderBottom: '1px solid var(--border)' }}>
                <td style={{ padding: '8px 0', fontSize: 13 }}>
                  <span style={{ color: (DB.brandByTag(sp.brand) && DB.brandByTag(sp.brand).color) || 'var(--ink-3)', fontWeight: 700, marginRight: 6, fontSize: 11 }}>{sp.brand}</span>
                  {sp.skuName}
                </td>
                <td style={{ padding: '8px', textAlign: 'center', fontSize: 12, color: 'var(--ink-4)' }}>{sp.inputUnit}</td>
                <td className="tnum" style={{ padding: '8px', textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{sp.planKor}</td>
                <td style={{ padding: '8px 0 8px 8px' }}>
                  <input
                    className="input tnum"
                    type="number"
                    min="0"
                    step="1"
                    placeholder="—"
                    value={vals[sp.skuId] ?? ''}
                    onChange={(e) => setVal(sp.skuId, e.target.value)}
                    style={{ width: '100%', height: 34, textAlign: 'right', fontSize: 13 }}
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
        <button className="btn btn--primary" disabled={busy || plans.length === 0} onClick={submit} style={{ height: 38 }}>
          {busy ? 'Saqlanmoqda…' : 'Saqlash'}
        </button>
      </div>
    </div>
  );
}

// ─── Asosiy komponent ─────────────────────────────────────────────────────────
function SelloutDashboard({ month: monthProp }) {
  const [month, setMonth]         = useState(monthProp || '2026-07');
  const [data, setData]           = useState(null);
  const [distributors, setDists]  = useState([]);
  const [loading, setLoading]     = useState(true);
  const [err, setErr]             = useState(null);
  const [expandedReg, setExpReg]  = useState({});
  const [tab, setTab]             = useState('dashboard'); // 'dashboard' | 'entry'
  const [toastMsg, setToastMsg]   = useState(null);

  function showToast(msg) { setToastMsg(msg); setTimeout(() => setToastMsg(null), 3000); }

  async function load(m) {
    setLoading(true); setErr(null);
    try {
      const [sum, dists] = await Promise.all([
        API.soSummary(m),
        API.soDistributors(),
      ]);
      setData(sum);
      setDists(dists.distributors || []);
    } catch (e) {
      setErr(e.message || 'Yuklab bo\'lmadi');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { load(month); }, [month]);

  function pickMonth(m) { setMonth(m); }
  function toggleReg(id) { setExpReg((p) => ({ ...p, [id]: !p[id] })); }

  const monthLabel = (SO_MONTHS.find((m) => m.key === month) || {}).label || month;

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px', background: 'var(--bg)' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20, flexWrap: 'wrap' }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 21, fontWeight: 800, letterSpacing: '-.02em' }}>
            SELL OUT — Kunlik ({monthLabel})
          </h2>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 3 }}>
            DB · Iyul 2026 dan boshlab yangi tizim
          </div>
        </div>
        <div style={{ flex: 1 }} />

        {/* Oy tanlash */}
        <select className="select" value={month} onChange={(e) => pickMonth(e.target.value)} style={{ height: 36, width: 130 }}>
          {SO_MONTHS.map((m) => <option key={m.key} value={m.key}>{m.label}</option>)}
        </select>

        {/* Tab */}
        {['dashboard', 'entry'].map((t) => (
          <button key={t} onClick={() => setTab(t)}
            className={tab === t ? 'btn btn--primary' : 'btn btn--ghost'}
            style={{ height: 36, fontSize: 13 }}>
            {t === 'dashboard' ? 'Dashboard' : 'Kiritish'}
          </button>
        ))}
      </div>

      {loading && <div style={{ color: 'var(--ink-4)', fontSize: 13 }}>Yuklanmoqda…</div>}
      {err && <div style={{ color: '#C2453A', fontSize: 13, background: 'rgba(232,115,95,.1)', padding: 12, borderRadius: 8 }}>{err}</div>}

      {/* ─ Dashboard ─ */}
      {!loading && !err && data && tab === 'dashboard' && (
        <>
          {/* KPI kartalar */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(170px,1fr))', gap: 12, marginBottom: 20 }}>
            <SoKpi label="Jami Plan"       value={soShort(data.kpi.planSom)}    sub={soFull(data.kpi.planSom) + ' so\'m'} />
            <SoKpi label="Jami Fakt"       value={soShort(data.kpi.faktSom)}    sub={soFull(data.kpi.faktSom) + ' so\'m'} color={data.kpi.foiz >= 1 ? '#1D8A6E' : undefined} />
            <SoKpi label="Bajarilish"      value={soPct(data.kpi.foiz)}         sub={`Prognoz: ${soPct(data.kpi.prognozFoiz)}`} color={data.kpi.foiz >= 0.7 ? '#1D8A6E' : '#C2453A'} />
            <SoKpi label="Kunlik Reja"     value={soShort(data.kpi.kunlikReja)} sub={`${data.period.totalWorkdays} ish kuni`} />
            <SoKpi label="Plan (kor)"      value={soKor(data.kpi.planKor)}      sub="karobka" />
            <SoKpi label="Fakt (kor)"      value={soKor(data.kpi.faktKor)}      sub="karobka" color={data.kpi.faktKor >= data.kpi.planKor ? '#1D8A6E' : undefined} />
          </div>

          {/* Oy sozlamalari qatori */}
          <PeriodSettingsBar period={data.period} month={month} onUpdated={() => load(month)} showToast={showToast} />

          {/* Regionlar jadvali */}
          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'hidden', boxShadow: 'var(--sh-1)' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '2px solid var(--border)', background: 'var(--bg-2,rgba(0,0,0,.03))' }}>
                  <th style={{ textAlign: 'left',  padding: '10px 14px', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>HUDUD</th>
                  <th style={{ textAlign: 'right', padding: '10px 12px', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>PLAN</th>
                  <th style={{ textAlign: 'right', padding: '10px 12px', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>KUNLIK</th>
                  <th style={{ textAlign: 'right', padding: '10px 12px', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>FAKT</th>
                  <th style={{ textAlign: 'right', padding: '10px 12px', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>%</th>
                  <th style={{ textAlign: 'right', padding: '10px 12px', fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>PLAN / FAKT (kor)</th>
                </tr>
              </thead>
              <tbody>
                {data.regions.map((reg) => (
                  <RegionRow key={reg.id} reg={reg} expanded={!!expandedReg[reg.id]} onToggle={() => toggleReg(reg.id)} />
                ))}
                {/* Jami qator */}
                <tr style={{ borderTop: '2px solid var(--border)', background: 'var(--bg-2,rgba(0,0,0,.04))' }}>
                  <td style={{ padding: '11px 14px', fontWeight: 800, fontSize: 13 }}>JAMI</td>
                  <td className="tnum" style={{ padding: '11px 12px', textAlign: 'right', fontWeight: 700 }}>{soShort(data.kpi.planSom)}</td>
                  <td className="tnum" style={{ padding: '11px 12px', textAlign: 'right', fontWeight: 700 }}>{soShort(data.kpi.kunlikReja)}</td>
                  <td className="tnum" style={{ padding: '11px 12px', textAlign: 'right', fontWeight: 800, color: data.kpi.foiz >= 0.7 ? '#1D8A6E' : '#C2453A' }}>{soShort(data.kpi.faktSom)}</td>
                  <td style={{ padding: '11px 12px', textAlign: 'right' }}>
                    <span style={{ ...soStatus(data.kpi.foiz), background: soStatus(data.kpi.foiz).tint, padding: '3px 9px', borderRadius: 999, fontSize: 12, fontWeight: 800 }}>
                      {soPct(data.kpi.foiz)}
                    </span>
                  </td>
                  <td className="tnum" style={{ padding: '11px 12px', textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{soKor(data.kpi.planKor)} / {soKor(data.kpi.faktKor)}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </>
      )}

      {/* ─ Kirish ─ */}
      {!loading && tab === 'entry' && (
        <EntryForm distributors={distributors} onSaved={() => load(month)} showToast={showToast} />
      )}

      {/* Toast */}
      {toastMsg && (
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
          background: '#1e293b', color: '#fff', padding: '10px 20px', borderRadius: 10,
          fontSize: 13.5, fontWeight: 600, zIndex: 9999, boxShadow: 'var(--sh-3)',
        }}>{toastMsg}</div>
      )}
    </div>
  );
}

// ─── Oy sozlamalari paneli ────────────────────────────────────────────────────
function PeriodSettingsBar({ period, month, onUpdated, showToast }) {
  const [editing, setEditing] = useState(false);
  const [tw, setTw]           = useState(period.totalWorkdays);
  const [pw, setPw]           = useState(period.passedWorkdays);
  const [busy, setBusy]       = useState(false);

  async function save() {
    setBusy(true);
    try {
      await API.soUpdateSettings({ month, totalWorkdays: parseInt(tw), passedWorkdays: parseInt(pw) });
      showToast('Sozlamalar saqlandi');
      setEditing(false);
      onUpdated();
    } catch (e) { showToast(e.message || 'Xatolik'); }
    finally { setBusy(false); }
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap',
                  background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
                  padding: '10px 16px', boxShadow: 'var(--sh-1)' }}>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-3)' }}>Ish kunlari:</span>
      {editing ? (
        <>
          <label style={{ fontSize: 12, color: 'var(--ink-4)' }}>Jami</label>
          <input className="input tnum" type="number" min="1" value={tw} onChange={(e) => setTw(e.target.value)}
            style={{ width: 64, height: 32, textAlign: 'center', fontSize: 13 }} />
          <label style={{ fontSize: 12, color: 'var(--ink-4)' }}>O'tgan</label>
          <input className="input tnum" type="number" min="0" value={pw} onChange={(e) => setPw(e.target.value)}
            style={{ width: 64, height: 32, textAlign: 'center', fontSize: 13 }} />
          <button className="btn btn--primary" style={{ height: 32, fontSize: 12 }} disabled={busy} onClick={save}>Saqlash</button>
          <button className="btn btn--ghost"   style={{ height: 32, fontSize: 12 }} onClick={() => setEditing(false)}>Bekor</button>
        </>
      ) : (
        <>
          <span className="tnum" style={{ fontSize: 13 }}>Jami: <b>{period.totalWorkdays}</b></span>
          <span className="tnum" style={{ fontSize: 13 }}>O'tgan: <b>{period.passedWorkdays}</b></span>
          <span className="tnum" style={{ fontSize: 13 }}>Qolgan: <b>{period.totalWorkdays - period.passedWorkdays}</b></span>
          <button className="btn btn--ghost" style={{ height: 32, fontSize: 12 }} onClick={() => setEditing(true)}>Tahrirlash</button>
        </>
      )}
    </div>
  );
}

window.SelloutDashboard = SelloutDashboard;
