/* ============================================================
   Zakaz detallari paneli + Deadline modali
   ============================================================ */

function OrderDetail({ order, perms, onClose, onEdit, onDelete, onSaveNote }) {
  const total = DB.orderTotal(order);
  const qty = DB.orderQty(order);
  const col = DB.COLUMNS[DB.COL_INDEX[order.status]];
  const deadline = DB.fmtDeadline(order.deadline);
  const [confirmDel, setConfirmDel] = useState(false);
  const [editingNote, setEditingNote] = useState(false);
  const [noteText, setNoteText] = useState(order.note || '');
  const [savingNote, setSavingNote] = useState(false);

  // Boshqa zakaz ochilsa — izoh matnini yangilaymiz
  useEffect(() => { setEditingNote(false); setNoteText(order.note || ''); }, [order.id]);

  async function saveNote() {
    if (!onSaveNote) { setEditingNote(false); return; }
    setSavingNote(true);
    try { await onSaveNote(order.id, noteText.trim()); setEditingNote(false); }
    catch (_) { /* xato toast yuqorida ko'rsatiladi */ }
    setSavingNote(false);
  }

  return (
    <div className="scrim" style={{ justifyContent: 'flex-end' }}
         onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ width: 480, maxWidth: 'calc(100vw - 36px)', height: '100%', background: 'var(--surface)',
                    boxShadow: 'var(--sh-3)', display: 'flex', flexDirection: 'column', animation: 'slideInRight .26s var(--ease)' }}>
        {/* Sarlavha */}
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span className="tnum" style={{ fontWeight: 800, fontSize: 17, letterSpacing: '-.01em' }}>{order.code}</span>
            <span className="chip" style={{ background: col.bg, color: col.color, fontWeight: 700 }}>
              <span className="dot" style={{ width: 7, height: 7, background: col.color }} /> {col.title.replace(' Zakazlar', '')}
            </span>
            <div style={{ flex: 1 }} />
            <button className="btn btn--icon btn--ghost" onClick={onClose} aria-label="Yopish"><Icon name="x" size={17} /></button>
          </div>
          <div style={{ fontWeight: 700, fontSize: 19, letterSpacing: '-.02em', marginTop: 12 }}>{DB.distributorName(order.distributorId)}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', fontSize: 13, marginTop: 4 }}>
            <Icon name="pin" size={14} stroke={1.8} /> {DB.regionName(order.region)}
          </div>
        </div>

        {/* Tana */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 22px' }}>
          {/* Meta kartalari */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 20 }}>
            {[
              ['SKU', order.lines.length + ' ta', 'layers'],
              ['Miqdor', qty + ' dona', 'box'],
              ['Deadline', deadline || '—', 'clock'],
            ].map(([k, v, ic], i) => (
              <div key={i} style={{ background: 'var(--bg)', borderRadius: 'var(--r-sm)', padding: '11px 12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: 'var(--ink-4)', fontWeight: 600, marginBottom: 5 }}>
                  <Icon name={ic} size={13} stroke={1.8} /> {k}
                </div>
                <div className="tnum" style={{ fontWeight: 700, fontSize: 13.5 }}>{v}</div>
              </div>
            ))}
          </div>

          {/* SKU jadvali */}
          <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 7 }}>
            Mahsulotlar ro'yxati
          </div>
          <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r)', overflow: 'hidden' }}>
            {order.lines.map((l, i) => {
              const p = DB.PRODUCT_BY_ID[l.productId];
              const brand = DB.brandOfProduct(l.productId);
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px',
                                      borderBottom: i < order.lines.length - 1 ? '1px solid var(--border)' : 'none' }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 3 }}>
                      <span style={{ fontWeight: 700, fontSize: 13 }}>{p ? p.name : '—'}</span>
                      {brand && <BrandTag brandId={brand.id} />}
                    </div>
                    <div className="tnum" style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>
                      {p ? p.sku : ''} · {DB.fmtSum(l.price)} so'm / {l.unit}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="tnum" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{l.qty} {l.unit}</div>
                    <div className="tnum" style={{ fontWeight: 700, fontSize: 13.5 }}>{DB.fmtSum(DB.lineTotal(l))}</div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Jami */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                        marginTop: 16, padding: '14px 16px', background: 'var(--brand-tint)', borderRadius: 'var(--r)' }}>
            <span style={{ fontWeight: 700, fontSize: 14, color: 'var(--brand-700)' }}>Umumiy summa</span>
            <span className="tnum" style={{ fontWeight: 800, fontSize: 20, letterSpacing: '-.02em', color: 'var(--brand-700)' }}>
              {DB.fmtSum(total)} <span style={{ fontSize: 13, fontWeight: 600 }}>so'm</span>
            </span>
          </div>

          {/* Qo'shimcha info */}
          <div style={{ marginTop: 20, fontSize: 12.5, color: 'var(--ink-3)', display: 'grid', gap: 7 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Javobgar menejer</span><span style={{ color: 'var(--ink)', fontWeight: 600 }}>{DB.orderManager(order) ? DB.orderManager(order).name : '\u2014'}</span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Yaratgan</span><span style={{ color: 'var(--ink)', fontWeight: 600 }}>{order.createdBy}</span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Yaratilgan sana</span><span className="tnum" style={{ color: 'var(--ink)', fontWeight: 600 }}>{new Date(order.createdAt).toLocaleDateString('ru-RU')}</span></div>
          </div>

          {/* Izoh — zakazni ko'rgan har kim tahrirlay oladi */}
          <div style={{ marginTop: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 9 }}>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-2)' }}>Izoh</span>
              {!editingNote && (
                <button className="btn btn--icon btn--ghost" style={{ padding: 4, border: 'none', color: 'var(--ink-4)' }}
                  onClick={() => { setNoteText(order.note || ''); setEditingNote(true); }} aria-label="Izohni tahrirlash">
                  <Icon name="edit" size={14} />
                </button>
              )}
            </div>
            {editingNote ? (
              <div>
                <textarea className="input" value={noteText} autoFocus rows={3}
                  onChange={e => setNoteText(e.target.value)}
                  placeholder="Zakaz bo'yicha izoh yozing…"
                  style={{ resize: 'vertical', minHeight: 60, fontFamily: 'inherit', lineHeight: 1.5 }} />
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
                  <button className="btn btn--ghost btn--sm" disabled={savingNote}
                    onClick={() => { setEditingNote(false); setNoteText(order.note || ''); }}>Bekor</button>
                  <button className="btn btn--primary btn--sm" disabled={savingNote} onClick={saveNote}>
                    <Icon name="check" size={14} stroke={2.4} /> {savingNote ? 'Saqlanmoqda…' : 'Saqlash'}
                  </button>
                </div>
              </div>
            ) : (
              order.note
                ? <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55, whiteSpace: 'pre-wrap',
                                background: 'var(--bg)', borderRadius: 'var(--r-sm)', padding: '11px 13px' }}>{order.note}</div>
                : <button onClick={() => { setNoteText(''); setEditingNote(true); }}
                    style={{ width: '100%', textAlign: 'left', fontSize: 12.5, color: 'var(--ink-4)', cursor: 'pointer',
                             background: 'var(--bg)', border: '1px dashed var(--border-2)', borderRadius: 'var(--r-sm)', padding: '11px 13px' }}>
                    + Izoh qo'shish…
                  </button>
            )}
          </div>
        </div>

        {/* Footer — istalgan zakazni tahrirlash / o'chirish */}
        {(perms.addOrder || perms.editOrder || onDelete) && (
          <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', gap: 10, alignItems: 'center' }}>
            {!confirmDel ? (
              <>
                {onDelete && (
                  <button className="btn btn--ghost" style={{ color: '#C2453A' }} onClick={() => setConfirmDel(true)}>
                    <Icon name="trash" size={15} /> O'chirish
                  </button>
                )}
                <div style={{ flex: 1 }} />
                {(perms.addOrder || perms.editOrder) && (
                  <button className="btn btn--primary" onClick={onEdit}>
                    <Icon name="edit" size={15} /> Tahrirlash
                  </button>
                )}
              </>
            ) : (
              <>
                <span style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 600 }}>Zakaz butunlay o'chirilsinmi?</span>
                <div style={{ flex: 1 }} />
                <button className="btn btn--ghost" onClick={() => setConfirmDel(false)}>Yo'q</button>
                <button className="btn btn--primary" style={{ background: '#C2453A' }} onClick={onDelete}>
                  <Icon name="trash" size={15} /> Ha, o'chirish
                </button>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Deadline modali ---------- */
function DeadlineModal({ order, onClose, onConfirm }) {
  const [date, setDate] = useState('2026-06-11');
  const [time, setTime] = useState('11:00');
  const [err, setErr] = useState('');

  function confirm() {
    if (!date || !time) { setErr('Sana va vaqtni kiriting'); return; }
    const iso = new Date(date + 'T' + time + ':00').toISOString();
    onConfirm(iso);
  }

  return (
    <Modal onClose={onClose} width={440}>
      <ModalHeader title="Yuklash deadline'i" onClose={onClose}
        subtitle={`${order ? order.code + ' — ' : ''}Rejalangan'ga o'tkazish uchun mashina yuklash muddatini kiriting`} />
      <div style={{ padding: '20px 22px' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '12px 14px', background: 'var(--st-planned-bg)',
                      borderRadius: 'var(--r-sm)', marginBottom: 20 }}>
          <span style={{ color: 'var(--st-planned)', marginTop: 1 }}><Icon name="info" size={17} /></span>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
            Bu maydon majburiy. Deadline'siz zakazni rejalashtirish mumkin emas.
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 12 }}>
          <div>
            <label className="field-label">Sana</label>
            <input className="input" type="date" value={date} onChange={e => { setDate(e.target.value); setErr(''); }} />
          </div>
          <div>
            <label className="field-label">Vaqt</label>
            <input className="input" type="time" value={time} onChange={e => { setTime(e.target.value); setErr(''); }} />
          </div>
        </div>
        {err && <div style={{ color: 'var(--st-loading)', fontSize: 12.5, fontWeight: 600, marginTop: 10 }}>{err}</div>}
      </div>
      <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
        <button className="btn btn--ghost" onClick={onClose}>Bekor qilish</button>
        <button className="btn btn--primary" onClick={confirm}>
          <Icon name="check" size={16} stroke={2.4} /> Rejalashtirish
        </button>
      </div>
    </Modal>
  );
}

Object.assign(window, { OrderDetail, DeadlineModal });
