/* ============================================================
   Zakaz qo'shish / tahrirlash formasi
   ============================================================ */
function OrderForm({ initial, user, onClose, onSave }) {
  const editing = !!initial;
  // Regional menejer faqat o'z viloyat(lar)idagi dillerlar uchun zakaz qo'shadi
  const myRegions = (user && user.regions) || [];
  const lockedRegion = myRegions.length === 1 ? myRegions[0] : null;
  const [region, setRegion] = useState(initial ? initial.region : (lockedRegion || 'all'));
  const [distributorId, setDistributorId] = useState(initial ? initial.distributorId : '');
  const [lines, setLines] = useState(initial ? initial.lines.map(l => ({ ...l, _id: Math.random() })) : []);
  const [note, setNote] = useState(initial ? (initial.note || '') : '');
  // Javobgar menejer — faqat super rol (general/boshliq) boshqa menejer nomidan
  // zakaz kiritganda tanlaydi. Bo'sh ('') = zakazni kiritgan o'ziga yoziladi.
  const isSuper = !!(user && DB.ROLES[user.role] && DB.ROLES[user.role].super);
  const managerUsers = useMemo(
    () => DB.USERS.filter(u => DB.ROLES[u.role] && DB.ROLES[u.role].perms && DB.ROLES[u.role].perms.addOrder),
    []
  );
  const [responsibleId, setResponsibleId] = useState(initial && initial.responsibleId ? initial.responsibleId : '');
  // Sell In limitini e'tiborsiz qoldirish — faqat super rol (boshliq/general) uchun.
  const [ignoreLimit, setIgnoreLimit] = useState(false);
  // Zakaz sanasi/vaqti — faqat super rol tahrirlay oladi (Dashboard oy filtri shunga tayanadi).
  // Lokal yordamchilar (global nom to'qnashuvidan saqlanish uchun komponent ichida).
  const ofPad = (n) => String(n).padStart(2, '0');
  const ofToDate = (iso) => { if (!iso) return ''; const d = new Date(iso); return isNaN(d) ? '' : `${d.getFullYear()}-${ofPad(d.getMonth() + 1)}-${ofPad(d.getDate())}`; };
  const ofToTime = (iso) => { if (!iso) return ''; const d = new Date(iso); return isNaN(d) ? '' : `${ofPad(d.getHours())}:${ofPad(d.getMinutes())}`; };
  const [orderDate, setOrderDate] = useState(initial && initial.createdAt ? ofToDate(initial.createdAt) : '');
  const [orderTime, setOrderTime] = useState(initial && initial.createdAt ? ofToTime(initial.createdAt) : '');
  const [brandTab, setBrandTab] = useState('all');
  const [search, setSearch] = useState('');
  const [dropActive, setDropActive] = useState(false);
  const [addPid, setAddPid] = useState('');
  const dragPid = useRef(null);

  const dists = useMemo(() => DB.DISTRIBUTORS.filter(d => {
    if (d.active === false && d.id !== distributorId) return false; // arxiv (joriy oyda yo'q) diller yashirin — tanlangani bundan mustasno
    if (myRegions.length && !myRegions.includes(d.region)) return false; // o'z viloyatlaridan tashqari diller ko'rinmaydi
    return region === 'all' || d.region === region;
  }), [region, distributorId]);

  // viloyat o'zgarsa, diller mos kelmasa tozalash
  useEffect(() => {
    if (distributorId && !dists.find(d => d.id === distributorId)) setDistributorId('');
  }, [region]);

  const catalog = useMemo(() => {
    return DB.PRODUCTS.filter(p => {
      const brand = DB.brandOfProduct(p.id);
      if (brandTab !== 'all' && brand?.id !== brandTab) return false;
      if (search && !p.name.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [brandTab, search]);

  // kategoriya bo'yicha guruhlash
  const grouped = useMemo(() => {
    const m = {};
    catalog.forEach(p => { (m[p.cat] = m[p.cat] || []).push(p); });
    return m;
  }, [catalog]);

  function addProduct(pid) {
    const p = DB.PRODUCT_BY_ID[pid]; if (!p) return;
    setLines(prev => {
      const ex = prev.find(l => l.productId === pid);
      if (ex) return prev.map(l => l.productId === pid ? { ...l, qty: l.qty + 1 } : l);
      return [...prev, { _id: Math.random(), productId: pid, qty: 1, unit: p.unit, price: p.price }];
    });
  }
  function updateLine(_id, patch) { setLines(prev => prev.map(l => l._id === _id ? { ...l, ...patch } : l)); }
  function removeLine(_id) { setLines(prev => prev.filter(l => l._id !== _id)); }

  const grandTotal = lines.reduce((s, l) => s + l.qty * l.price, 0);
  const grandQty = lines.reduce((s, l) => s + l.qty, 0);
  const canSave = distributorId && lines.length > 0 && lines.every(l => l.qty > 0);
  // Ikki marta yuborilishdan himoya (double-click → 2 ta zakaz bo'lib ketmasin).
  const [busy, setBusy] = useState(false);

  async function save() {
    if (!canSave || busy) return;
    setBusy(true);
    const dist = DB.DISTRIBUTORS.find(d => d.id === distributorId);
    try {
      await onSave({
      ...(initial || {}),
      distributorId,
      region: dist.region,
      note: note.trim(),
      // Javobgar menejer — faqat super rol uchun yuboriladi (aks holda backend e'tibor bermaydi).
      // '' → null (zakazni kiritgan o'ziga yoziladi).
      responsibleId: isSuper ? (responsibleId || null) : (initial ? (initial.responsibleId || null) : null),
      // Limitni e'tiborsiz qoldirish — faqat super rol uchun yuboriladi.
      ignoreLimit: isSuper ? ignoreLimit : undefined,
      // Zakaz sanasi — faqat super rol va sana tanlansa (ISO). Aks holda yuborilmaydi.
      createdAt: (isSuper && orderDate) ? new Date(`${orderDate}T${orderTime || '12:00'}`).toISOString() : undefined,
      lines: lines.map(({ _id, ...l }) => l),
      }, editing);
    } finally {
      setBusy(false);
    }
  }

  return (
    <Modal onClose={onClose} width={920} align="stretch">
      <ModalHeader title={editing ? 'Zakazni tahrirlash' : 'Yangi zakaz'}
        subtitle="Dillerni tanlang, so'ng mahsulotlarni katalogdan sudrab yoki tanlab qo'shing"
        onClose={onClose} />

      {/* Diller tanlash satri */}
      <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--border)', background: 'var(--bg)', display: 'grid', gap: 12 }}>
        <div style={{ display: 'flex', gap: 12 }}>
          <div style={{ width: 220 }}>
            <label className="field-label">Viloyat</label>
            <select className="select" value={region} onChange={e => setRegion(e.target.value)} disabled={!!lockedRegion}>
              {!lockedRegion && <option value="all">{myRegions.length ? 'Barcha viloyatlarim' : 'Barcha viloyatlar'}</option>}
              {(myRegions.length ? DB.REGIONS.filter(r => myRegions.includes(r.id)) : DB.REGIONS).filter(r => r.active !== false || r.id === region).map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
            </select>
          </div>
          <div style={{ flex: 1 }}>
            <label className="field-label">Diller</label>
            <select className="select" value={distributorId} onChange={e => setDistributorId(e.target.value)}>
              <option value="">— Dillerni tanlang —</option>
              {dists.map(d => <option key={d.id} value={d.id}>{d.name} · {DB.regionName(d.region)}</option>)}
            </select>
          </div>
          {isSuper && (
            <div style={{ width: 240 }}>
              <label className="field-label">Javobgar menejer</label>
              <select className="select" value={responsibleId} onChange={e => setResponsibleId(e.target.value)}
                title="Zakaz puli (reyting) shu menejerga yoziladi">
                <option value="">— O'zim (zakazni kiritgan) —</option>
                {managerUsers.map(u => <option key={u.id} value={u.id}>{u.name} · {DB.ROLES[u.role]?.short || u.role}</option>)}
              </select>
            </div>
          )}
        </div>
        {/* Zakaz sanasi/vaqti — faqat super rol (Dashboard oy filtri shunga tayanadi) */}
        {isSuper && (
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end' }}>
            <div style={{ width: 220 }}>
              <label className="field-label">Zakaz sanasi</label>
              <input className="input" type="date" value={orderDate} onChange={e => setOrderDate(e.target.value)}
                title="Zakaz kiritilgan sana — bo'sh bo'lsa hozirgi vaqt (faqat boshliq/general tahrirlaydi)" />
            </div>
            <div style={{ width: 130 }}>
              <label className="field-label">Soat (ixtiyoriy)</label>
              <input className="input" type="time" value={orderTime} disabled={!orderDate} onChange={e => setOrderTime(e.target.value)} />
            </div>
            {orderDate && (
              <button type="button" className="btn btn--ghost btn--sm" onClick={() => { setOrderDate(''); setOrderTime(''); }}
                style={{ marginBottom: 1 }} title="Sanani tozalash (hozirgi vaqt qo'yiladi)">Tozalash</button>
            )}
          </div>
        )}
        <div>
          <label className="field-label">Izoh</label>
          <textarea className="input" value={note} onChange={e => setNote(e.target.value)} rows={2}
            placeholder="Zakaz bo'yicha qo'shimcha izoh (ixtiyoriy)…"
            style={{ resize: 'vertical', minHeight: 38, fontFamily: 'inherit', lineHeight: 1.45 }} />
        </div>
      </div>

      {/* Asosiy: katalog | tarkib */}
      <div className="modal-2col" style={{ display: 'grid', gridTemplateColumns: '340px 1fr', flex: 1, minHeight: 0 }}>
        {/* Katalog */}
        <div style={{ borderRight: '1px solid var(--border)', display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg)' }}>
          <div style={{ padding: '12px 14px 8px' }}>
            <div style={{ position: 'relative', marginBottom: 9 }}>
              <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-4)' }}><Icon name="search" size={15} /></span>
              <input className="input" style={{ paddingLeft: 32 }} placeholder="Mahsulot qidirish…" value={search} onChange={e => setSearch(e.target.value)} />
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {[['all', 'Hammasi'], ...DB.BRANDS.map(b => [b.id, b.name])].map(([k, lbl]) => (
                <button key={k} onClick={() => setBrandTab(k)}
                  style={{ flex: 1, padding: '6px 8px', borderRadius: 7, fontSize: 12, fontWeight: 700, border: '1px solid var(--border)',
                           background: brandTab === k ? 'var(--brand)' : 'var(--surface)', color: brandTab === k ? '#fff' : 'var(--ink-2)' }}>
                  {lbl}
                </button>
              ))}
            </div>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '4px 14px 14px' }}>
            {Object.keys(grouped).length === 0 && <Empty icon="search" text="Mahsulot topilmadi" />}
            {DB.CATEGORIES.filter(c => grouped[c.id]).map(c => (
              <div key={c.id} style={{ marginBottom: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, margin: '4px 2px 7px' }}>
                  <BrandTag brandId={c.brand} />
                  <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)' }}>{c.name}</span>
                </div>
                <div style={{ display: 'grid', gap: 6 }}>
                  {grouped[c.id].map(p => (
                    <div key={p.id} draggable
                      onDragStart={(e) => { dragPid.current = p.id; e.dataTransfer.effectAllowed = 'copy'; try { e.dataTransfer.setData('text/plain', p.id); } catch (_) {} }}
                      onDragEnd={() => { dragPid.current = null; }}
                      onClick={() => addProduct(p.id)}
                      title="Sudrab tashlang yoki bosing"
                      style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 10px', background: 'var(--surface)',
                               border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', cursor: 'grab', transition: 'all .13s var(--ease)' }}
                      onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--brand)'; e.currentTarget.style.boxShadow = 'var(--sh-1)'; }}
                      onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.boxShadow = 'none'; }}>
                      <span style={{ color: 'var(--ink-4)', cursor: 'grab' }}><Icon name="drag" size={15} /></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
                        <div className="tnum" style={{ fontSize: 11, color: 'var(--ink-4)' }}>{DB.fmtSum(p.price)} so'm · {p.unit}</div>
                      </div>
                      <span style={{ color: 'var(--brand)' }}><Icon name="plus" size={15} stroke={2.4} /></span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Tarkib (drop zone) */}
        <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div
            onDragOver={(e) => { e.preventDefault(); setDropActive(true); }}
            onDragLeave={(e) => { if (e.currentTarget === e.target) setDropActive(false); }}
            onDrop={(e) => { e.preventDefault(); setDropActive(false); const pid = dragPid.current || e.dataTransfer.getData('text/plain'); if (pid) addProduct(pid); }}
            style={{ flex: 1, overflowY: 'auto', padding: '14px 18px',
                     background: dropActive ? 'var(--brand-tint)' : 'transparent',
                     outline: dropActive ? '2px dashed var(--brand)' : '2px dashed transparent', outlineOffset: -8, transition: 'all .15s' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <span style={{ fontWeight: 700, fontSize: 13.5 }}>Zakaz tarkibi</span>
              <span className="chip">{lines.length} pozitsiya</span>
            </div>

            {lines.length === 0 && (
              <div style={{ border: '2px dashed var(--border-2)', borderRadius: 'var(--r-lg)', padding: '38px 20px', textAlign: 'center', color: 'var(--ink-4)' }}>
                <div style={{ display: 'inline-flex', padding: 14, borderRadius: '50%', background: 'var(--bg-2)', marginBottom: 12 }}>
                  <Icon name="box" size={26} stroke={1.6} />
                </div>
                <div style={{ fontWeight: 600, fontSize: 13.5, color: 'var(--ink-3)' }}>Mahsulotni shu yerga sudrab tashlang</div>
                <div style={{ fontSize: 12, marginTop: 4 }}>yoki katalogdan bosib qo'shing</div>
              </div>
            )}

            <div style={{ display: 'grid', gap: 8 }}>
              {lines.map(l => {
                const p = DB.PRODUCT_BY_ID[l.productId];
                const brand = DB.brandOfProduct(l.productId);
                return (
                  <div key={l._id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                                            border: '1px solid var(--border)', borderRadius: 'var(--r)', background: 'var(--surface)' }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ fontWeight: 700, fontSize: 13 }}>{p.name}</span>
                        {brand && <BrandTag brandId={brand.id} />}
                      </div>
                      <div className="tnum" style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{DB.fmtSum(l.price)} so'm / {l.unit}</div>
                    </div>
                    {/* miqdor */}
                    <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--border-2)', borderRadius: 7, overflow: 'hidden' }}>
                      <button className="qbtn" onClick={() => updateLine(l._id, { qty: Math.max(1, l.qty - 1) })}
                        style={{ width: 28, height: 30, border: 'none', background: 'var(--bg)', color: 'var(--ink-2)', fontSize: 16, lineHeight: 1 }}>−</button>
                      <input className="tnum" value={l.qty}
                        onChange={e => { const v = parseInt(e.target.value.replace(/\D/g, '') || '0', 10); updateLine(l._id, { qty: v }); }}
                        onBlur={e => { if (!l.qty || l.qty < 1) updateLine(l._id, { qty: 1 }); }}
                        style={{ width: 42, textAlign: 'center', border: 'none', outline: 'none', fontWeight: 700, fontSize: 13, height: 30 }} />
                      <button className="qbtn" onClick={() => updateLine(l._id, { qty: l.qty + 1 })}
                        style={{ width: 28, height: 30, border: 'none', background: 'var(--bg)', color: 'var(--ink-2)', fontSize: 16, lineHeight: 1 }}>+</button>
                    </div>
                    {/* unit */}
                    <select className="select" value={l.unit} onChange={e => updateLine(l._id, { unit: e.target.value })}
                      style={{ width: 96, padding: '7px 9px', paddingRight: 26, fontSize: 12.5 }}>
                      <option value="blok">blok</option>
                      <option value="karobka">karobka</option>
                    </select>
                    {/* line total */}
                    <div className="tnum" style={{ width: 96, textAlign: 'right', fontWeight: 800, fontSize: 13.5 }}>{DB.fmtSum(l.qty * l.price)}</div>
                    <button className="btn btn--icon btn--ghost" onClick={() => removeLine(l._id)} style={{ padding: 6, borderColor: 'transparent', color: 'var(--ink-4)' }} aria-label="O'chirish">
                      <Icon name="trash" size={15} />
                    </button>
                  </div>
                );
              })}
            </div>

            {/* Fallback dropdown */}
            <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
              <select className="select" value={addPid} onChange={e => setAddPid(e.target.value)} style={{ flex: 1, fontSize: 12.5 }}>
                <option value="">+ Mahsulot tanlab qo'shish…</option>
                {DB.BRANDS.map(b => (
                  <optgroup key={b.id} label={b.name}>
                    {DB.PRODUCTS.filter(p => DB.brandOfProduct(p.id)?.id === b.id).map(p =>
                      <option key={p.id} value={p.id}>{p.name} — {DB.fmtSum(p.price)} so'm</option>)}
                  </optgroup>
                ))}
              </select>
              <button className="btn btn--ghost" disabled={!addPid} onClick={() => { addProduct(addPid); setAddPid(''); }}>
                <Icon name="plus" size={15} stroke={2.2} /> Qo'shish
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Footer — grand total */}
      <div className="modal-foot" style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 22px', borderTop: '1px solid var(--border)', background: 'var(--surface)' }}>
        <div style={{ display: 'flex', gap: 22 }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 600 }}>Miqdor</div>
            <div className="tnum" style={{ fontWeight: 700, fontSize: 15 }}>{grandQty} <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>dona</span></div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 600 }}>Umumiy summa</div>
            <div className="tnum" style={{ fontWeight: 800, fontSize: 19, letterSpacing: '-.02em', color: 'var(--brand-700)' }}>{DB.fmtSum(grandTotal)} <span style={{ fontSize: 12, fontWeight: 600 }}>so'm</span></div>
          </div>
        </div>
        <div style={{ flex: 1 }} />
        {isSuper && (
          <label style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12, color: 'var(--ink-3)', cursor: 'pointer', userSelect: 'none' }}
            title="Sell In (jadval) limitidan oshsa ham zakazni kiritish — faqat boshliq/general">
            <input type="checkbox" checked={ignoreLimit} onChange={e => setIgnoreLimit(e.target.checked)} />
            Limitni e'tiborsiz qoldirish
          </label>
        )}
        <button className="btn btn--ghost" onClick={onClose}>Bekor qilish</button>
        <button className="btn btn--primary" disabled={!canSave || busy} onClick={save}>
          <Icon name="check" size={16} stroke={2.4} /> {busy ? 'Saqlanmoqda…' : (editing ? 'Saqlash' : 'Zakazni yaratish')}
        </button>
      </div>
    </Modal>
  );
}

window.OrderForm = OrderForm;
