/* ============================================================
   Do'kon bazasi (AKB) — savdo nuqtalari registri.
   Har do'kon viloyat + (ixtiyoriy) distributorga bog'lanadi. Storecheck'dagi
   do'kon nomlaridan avtomatik to'ldirish mumkin ("Storecheck'dan import").
   Ruxsat: super — hammasi; regional — faqat o'z viloyat(lar)i. /api/outlets.
   scRegionOptions/scIsSuper — storecheck.jsx'dan (umumiy scope).
   ============================================================ */

const OUTLET_CHANNELS = ["Do'kon", 'Market', 'Supermarket', 'Optom', 'Pavilion', 'Avtolavka', 'Boshqa'];

function OutletModal({ initial, regionOpts, onClose, onSaved, showToast }) {
  const isNew = !initial.id;
  const [name, setName] = useState(initial.name || '');
  const [regionId, setRegionId] = useState(initial.regionId || (regionOpts[0] && regionOpts[0].id) || '');
  const [distributorId, setDistributorId] = useState(initial.distributorId || '');
  const [channel, setChannel] = useState(initial.channel || '');
  const [agent, setAgent] = useState(initial.agent || '');
  const [address, setAddress] = useState(initial.address || '');
  const [active, setActive] = useState(initial.active !== false);
  const [busy, setBusy] = useState(false);

  const dists = (DB.DISTRIBUTORS || []).filter((d) => d.region === regionId);

  async function save() {
    if (!name.trim()) return showToast('Do`kon nomini kiriting');
    if (!regionId) return showToast('Viloyatni tanlang');
    setBusy(true);
    try {
      const payload = {
        name: name.trim(), regionId, distributorId: distributorId || null,
        channel: channel || null, agent: agent || null, address: address || null, active,
      };
      const r = isNew ? await API.createOutlet(payload) : await API.updateOutlet(initial.id, payload);
      showToast(isNew ? "Do'kon qo'shildi" : 'Saqlandi');
      onSaved(r.outlet);
      onClose();
    } catch (ex) { showToast((ex && ex.message) || 'Saqlashda xatolik'); setBusy(false); }
  }

  const field = (label, node) => (
    <label style={{ display: 'block' }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>
      {node}
    </label>
  );

  return (
    <Modal onClose={onClose} width={520}>
      <ModalHeader title={isNew ? "Yangi do'kon" : "Do'konni tahrirlash"} subtitle="Savdo nuqtasi (AKB)" onClose={onClose} />
      <div style={{ padding: 20, display: 'grid', gap: 13 }}>
        {field('Do`kon nomi *', <input className="input" value={name} onChange={(e) => setName(e.target.value)} style={{ width: '100%' }} placeholder="Masalan: Anvar magazin" />)}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          {field('Viloyat *', (
            <select className="input" value={regionId} onChange={(e) => { setRegionId(e.target.value); setDistributorId(''); }} style={{ width: '100%' }}>
              <option value="">— tanlang —</option>
              {regionOpts.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
          ))}
          {field('Distributor', (
            <select className="input" value={distributorId} onChange={(e) => setDistributorId(e.target.value)} style={{ width: '100%' }}>
              <option value="">— yo'q —</option>
              {dists.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
            </select>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 13 }}>
          {field('Kanal (tur)', (
            <>
              <input className="input" list="outlet-channels" value={channel} onChange={(e) => setChannel(e.target.value)} style={{ width: '100%' }} placeholder="Do'kon / Market…" />
              <datalist id="outlet-channels">{OUTLET_CHANNELS.map((c) => <option key={c} value={c} />)}</datalist>
            </>
          ))}
          {field('Savdo vakili (Т.П)', <input className="input" value={agent} onChange={(e) => setAgent(e.target.value)} style={{ width: '100%' }} />)}
        </div>
        {field('Manzil', <input className="input" value={address} onChange={(e) => setAddress(e.target.value)} style={{ width: '100%' }} />)}
        <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Faol (AKB hisobiga kiradi)</span>
        </label>
      </div>
      <div style={{ display: 'flex', gap: 10, padding: '14px 20px', borderTop: '1px solid var(--border)', justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor qilish</button>
        <button className="btn btn--primary" onClick={save} disabled={busy}><Icon name="check" size={15} stroke={2.4} /> Saqlash</button>
      </div>
    </Modal>
  );
}

function OutletsStat({ 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)' }}>{value}</div>
      {sub != null && <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

function Outlets({ user, showToast }) {
  const [outlets, setOutlets] = useState([]);
  const [summary, setSummary] = useState(null);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [q, setQ] = useState('');
  const [regionF, setRegionF] = useState('');
  const [activeF, setActiveF] = useState('all'); // all | active | inactive
  const [editing, setEditing] = useState(null);

  const regionOpts = scRegionOptions(user);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [a, b] = await Promise.all([API.listOutlets(), API.outletsSummary()]);
      setOutlets(a.outlets || []);
      setSummary(b);
    } catch (ex) { showToast((ex && ex.message) || 'Yuklashda xatolik'); }
    finally { setLoading(false); }
  }, [showToast]);
  useEffect(() => { load(); }, [load]);

  async function doSync() {
    if (!window.confirm("Storecheck'dagi do'kon nomlaridan bazaga yangi do'konlar qo'shilsinmi?")) return;
    setBusy(true);
    try {
      const r = await API.syncOutlets();
      showToast(r.created > 0 ? (r.created + " ta yangi do'kon qo'shildi") : "Yangi do'kon topilmadi");
      await load();
    } catch (ex) { showToast((ex && ex.message) || 'Import xatosi'); }
    finally { setBusy(false); }
  }

  async function toggleActive(o) {
    try {
      const r = await API.updateOutlet(o.id, { active: !o.active });
      setOutlets((prev) => prev.map((x) => (x.id === o.id ? r.outlet : x)));
      setSummary(null); load();
    } catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }
  async function remove(o) {
    if (!window.confirm('"' + o.name + '" o`chirilsinmi?')) return;
    try { await API.deleteOutlet(o.id); setOutlets((prev) => prev.filter((x) => x.id !== o.id)); load(); showToast("O'chirildi"); }
    catch (ex) { showToast((ex && ex.message) || 'Xatolik'); }
  }
  function onSaved() { load(); }

  const list = useMemo(() => {
    const needle = q.trim().toLowerCase();
    return outlets.filter((o) => {
      if (regionF && o.regionId !== regionF) return false;
      if (activeF === 'active' && !o.active) return false;
      if (activeF === 'inactive' && o.active) return false;
      if (needle && !(o.name || '').toLowerCase().includes(needle) && !(o.agent || '').toLowerCase().includes(needle)) return false;
      return true;
    });
  }, [outlets, q, regionF, activeF]);

  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 }}>Do'konlar (AKB)</h2>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>Savdo nuqtalari bazasi · faol mijozlar</div>
        </div>
        <div style={{ flex: 1 }} />
        <button className="btn btn--ghost" style={{ height: 38 }} onClick={doSync} disabled={busy}>
          <Icon name="layers" size={16} /> Storecheck'dan import
        </button>
        <button className="btn btn--primary" style={{ height: 38 }} onClick={() => setEditing({})} disabled={!regionOpts.length}>
          <Icon name="plus" size={16} stroke={2.4} /> Yangi do'kon
        </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>
        ) : (
          <>
            {summary && (
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
                <OutletsStat label="Jami do'kon" value={summary.summary.total} />
                <OutletsStat label="Faol (AKB)" value={summary.summary.active} accent="#1D8A6E" sub={summary.summary.total ? Math.round(summary.summary.active / summary.summary.total * 100) + '%' : null} />
                <OutletsStat label="Viloyatlar" value={summary.summary.regions} />
              </div>
            )}

            {/* Filtrlar */}
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 14 }}>
              <input className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Qidirish (nom / agent)…" style={{ height: 34, width: 200 }} />
              <select className="input" value={regionF} onChange={(e) => setRegionF(e.target.value)} style={{ height: 34 }}>
                <option value="">Barcha viloyatlar</option>
                {regionOpts.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
              </select>
              <select className="input" value={activeF} onChange={(e) => setActiveF(e.target.value)} style={{ height: 34 }}>
                <option value="all">Hammasi</option>
                <option value="active">Faqat faol</option>
                <option value="inactive">Faqat nofaol</option>
              </select>
              <div style={{ alignSelf: 'center', fontSize: 12, color: 'var(--ink-4)' }}>{list.length} ta</div>
            </div>

            {list.length === 0 ? (
              <Empty icon="box" text="Do'kon topilmadi. “Storecheck'dan import” yoki “Yangi do'kon” bilan boshlang." />
            ) : (
              <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', overflow: 'auto', background: 'var(--surface)' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 720 }}>
                  <thead>
                    <tr style={{ textAlign: 'left', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em', background: 'var(--bg-2)' }}>
                      <th style={{ padding: '9px 14px' }}>Do'kon</th>
                      <th style={{ padding: '9px 12px' }}>Viloyat</th>
                      <th style={{ padding: '9px 12px' }}>Distributor</th>
                      <th style={{ padding: '9px 12px' }}>Kanal</th>
                      <th style={{ padding: '9px 12px' }}>Agent</th>
                      <th style={{ padding: '9px 12px', textAlign: 'center' }}>Faol</th>
                      <th style={{ padding: '9px 12px' }} />
                    </tr>
                  </thead>
                  <tbody>
                    {list.map((o) => (
                      <tr key={o.id} style={{ borderTop: '1px solid var(--border)' }}>
                        <td style={{ padding: '9px 14px', fontWeight: 700 }}>{o.name}</td>
                        <td style={{ padding: '9px 12px', color: 'var(--ink-3)' }}>{o.regionName || '—'}</td>
                        <td style={{ padding: '9px 12px', color: 'var(--ink-3)' }}>{o.distributorName || '—'}</td>
                        <td style={{ padding: '9px 12px', color: 'var(--ink-3)' }}>{o.channel || '—'}</td>
                        <td style={{ padding: '9px 12px', color: 'var(--ink-3)' }}>{o.agent || '—'}</td>
                        <td style={{ padding: '9px 12px', textAlign: 'center' }}>
                          <button onClick={() => toggleActive(o)} title="Faollikni o'zgartirish"
                            style={{ border: 'none', cursor: 'pointer', borderRadius: 999, padding: '2px 10px', fontSize: 11, fontWeight: 800,
                                     background: o.active ? 'rgba(61,190,156,.14)' : 'var(--bg-2)', color: o.active ? '#1D8A6E' : 'var(--ink-4)' }}>
                            {o.active ? 'Faol' : 'Nofaol'}
                          </button>
                        </td>
                        <td style={{ padding: '9px 12px', whiteSpace: 'nowrap', textAlign: 'right' }}>
                          <button className="btn btn--icon btn--ghost" onClick={() => setEditing(o)} title="Tahrirlash" style={{ width: 28, height: 28 }}><Icon name="edit" size={14} /></button>
                          <button className="btn btn--icon btn--ghost" onClick={() => remove(o)} title="O'chirish" style={{ width: 28, height: 28, color: '#C2453A' }}><Icon name="trash" size={14} /></button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </>
        )}
      </div>

      {editing && (
        <OutletModal initial={editing} regionOpts={regionOpts} onClose={() => setEditing(null)} onSaved={onSaved} showToast={showToast} />
      )}
    </div>
  );
}
