// party-picker.jsx — shared Customer + Representative picker with inline "add new".
// Used by quote-new.jsx and contract-new.jsx. Lets a user create a customer or a
// contact directly on the form (without leaving to the Customers/Contacts modules).
function PartyFields({ customer, rep, onCustomer, onRep, showEmail }){
  const p = usePortal();
  const { t, lang } = useLang();
  const toast = useToast();

  const [addingCust, setAddingCust] = React.useState(false);
  const [addingRep, setAddingRep] = React.useState(false);
  const [nc, setNc] = React.useState({ name:'', mst:'', addr:'' });
  const [nr, setNr] = React.useState({ name:'', title:'', email:'', phone:'' });

  const cust = p.customers.find(c => c.code === customer) || {};
  const reps = p.contacts.filter(c => c.customer === customer);
  const repObj = p.contacts.find(c => c.code === rep) || {};

  const L = (vi, en) => (lang === 'vi' ? vi : en);

  // ----- tra cứu doanh nghiệp theo MST (VietQR, client-side) → tự điền tên + địa chỉ -----
  const [looking, setLooking] = React.useState(false);
  const lookupMst = async () => {
    const mst = nc.mst.trim();
    if (!mst){ toast(L('Nhập mã số thuế trước', 'Enter tax ID first'), 'error'); return; }
    setLooking(true);
    try {
      const r = await fetch('https://api.vietqr.io/v2/business/' + encodeURIComponent(mst));
      const j = await r.json().catch(() => null);
      if (j && j.code === '00' && j.data && j.data.name){
        setNc(s => ({ ...s, name:j.data.name, addr:j.data.address || s.addr }));
        toast(L('Đã lấy thông tin doanh nghiệp', 'Company info fetched'), 'success');
      } else {
        toast(L('Không tìm thấy doanh nghiệp với MST này', 'No business found for this tax ID'), 'error');
      }
    } catch (e){ toast((L('Tra cứu thất bại: ', 'Lookup failed: ')) + (e.message || e), 'error'); }
    finally { setLooking(false); }
  };

  // ----- create a new customer inline -----
  const saveCust = () => {
    const name = nc.name.trim();
    if (!name){ toast(L('Nhập tên khách hàng', 'Enter a customer name'), 'error'); return; }
    const code = genCustomerCode(name);
    if (!code || p.customers.some(c => c.code === code)){ toast(L('Mã KH bị trùng, sửa tên', 'Code clashes — adjust name'), 'error'); return; }
    p.addCustomer({ name, shortName:name.split(' ')[0], code, lang:'vi', mst:nc.mst.trim(), address:nc.addr.trim() || null, industry:INDUSTRIES[0], country:'VN', owner:p.me.name, status:'prospect' });
    if (nc.addr.trim()) CUSTOMER_ADDR[code] = nc.addr.trim();
    onCustomer(code); onRep('');
    setAddingCust(false); setNc({ name:'', mst:'', addr:'' });
    toast(L('Đã thêm KH ', 'Added ') + code, 'success');
  };

  // ----- create a new contact (representative) inline, tied to current customer -----
  const saveRep = () => {
    if (!customer){ toast(L('Chọn khách hàng trước', 'Select a customer first'), 'error'); return; }
    const name = nr.name.trim();
    if (!name){ toast(L('Nhập họ tên', 'Enter a name'), 'error'); return; }
    const code = genContactCode(p.contacts);
    p.addContact({ code, name, native:'', title:nr.title.trim(), email:nr.email.trim(), phone:nr.phone.trim(), type:'lead', nationality:'VN', customer, owner:p.me.name, status:'active', tx:[] });
    onRep(code);
    setAddingRep(false); setNr({ name:'', title:'', email:'', phone:'' });
    toast(L('Đã thêm liên hệ ', 'Added ') + code, 'success');
  };

  const headRow = (label, btnLabel, onClick, disabled) => (
    <div className="flex justify-between items-center" style={{ minHeight:22 }}>
      <label style={{ fontSize:'var(--fs-base)', fontWeight:500, color:'var(--text-muted)' }}>{label}</label>
      <button className="btn btn-ghost btn-sm" style={{ height:22, padding:'0 6px', color:'var(--primary)' }} disabled={disabled} onClick={onClick}>
        <i className="bi bi-plus-lg" style={{ fontSize:11 }}></i>{btnLabel}
      </button>
    </div>
  );

  const panelStyle = { background:'var(--bg-subtle)', border:'1px solid var(--border)', borderRadius:'var(--r-md)', padding:'12px 12px 14px' };

  return (
    <React.Fragment>
      <div className="flex g12 wrap">
        {/* customer */}
        <div className="col g5" style={{ flex:'1 1 240px', gap:5, display:'flex', flexDirection:'column' }}>
          {headRow(t('ct.customer'), L('Thêm mới', 'New'), () => { setAddingCust(v => !v); }, false)}
          <select className="select" value={customer} onChange={e => { onCustomer(e.target.value); onRep(''); }}>
            {!p.customers.length && <option value="">— {L('chưa có KH', 'no customers')} —</option>}
            {p.customers.map(c => <option key={c.code} value={c.code}>{c.code} · {c.name}</option>)}
          </select>
        </div>
        {/* representative */}
        <div className="col g5" style={{ flex:'1 1 240px', gap:5, display:'flex', flexDirection:'column' }}>
          {headRow(t('hd.rep') + ' (' + L('từ Liên hệ', 'from Contacts') + ')', L('Thêm mới', 'New'), () => { setAddingRep(v => !v); }, !customer)}
          <select className="select" value={rep} onChange={e => onRep(e.target.value)}>
            <option value="">— {reps.length ? L('chọn', 'select') : L('không có liên hệ', 'no contacts')} —</option>
            {reps.map(r => <option key={r.code} value={r.code}>{r.name}{r.title ? ' · ' + r.title : ''}</option>)}
          </select>
        </div>
      </div>

      {/* inline: new customer */}
      {addingCust && (
        <div style={panelStyle}>
          <div className="flex justify-between items-center" style={{ marginBottom:10 }}>
            <span style={{ fontWeight:600, fontSize:'var(--fs-md)' }}><i className="bi bi-building-add" style={{ marginRight:6, color:'var(--primary)' }}></i>{L('Khách hàng mới', 'New customer')}</span>
            <button className="iconbtn" style={{ width:24, height:24 }} onClick={() => setAddingCust(false)}><i className="bi bi-x-lg" style={{ fontSize:13 }}></i></button>
          </div>
          <div className="col g10" style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <Field label={t('cust.name')}><input className="input" autoFocus value={nc.name} onChange={e => setNc(s => ({ ...s, name:e.target.value }))} placeholder={L('VD: Công ty TNHH ABC', 'e.g. ABC Company Ltd')} onKeyDown={e => { if (e.key === 'Enter'){ e.preventDefault(); saveCust(); } }} /></Field>
            <div className="flex g12 wrap">
              <div style={{ flex:'1 1 160px' }}><Field label={t('cust.mst')} hint={L('Bấm tra cứu để tự điền tên + địa chỉ', 'Look up to autofill name + address')}>
                <div className="flex g8 items-center">
                  <input className="input mono" value={nc.mst} onChange={e => setNc(s => ({ ...s, mst:e.target.value }))} placeholder="0300000000" onKeyDown={e => { if (e.key === 'Enter'){ e.preventDefault(); lookupMst(); } }} />
                  <button className="btn btn-sm" onClick={lookupMst} disabled={looking} title={t('cust.lookup')}>{looking ? <i className="bi bi-arrow-repeat spin"></i> : <i className="bi bi-search"></i>}</button>
                </div>
              </Field></div>
              <div style={{ flex:'2 1 260px' }}><Field label={t('hd.address')}><input className="input" value={nc.addr} onChange={e => setNc(s => ({ ...s, addr:e.target.value }))} placeholder={L('Địa chỉ trụ sở', 'Head-office address')} /></Field></div>
            </div>
            <div className="flex g8 justify-end">
              <button className="btn btn-sm" onClick={() => setAddingCust(false)}>{t('c.cancel')}</button>
              <button className="btn btn-sm btn-primary" onClick={saveCust}><i className="bi bi-check-lg"></i>{L('Lưu khách hàng', 'Save customer')}</button>
            </div>
          </div>
        </div>
      )}

      {/* inline: new representative */}
      {addingRep && customer && (
        <div style={panelStyle}>
          <div className="flex justify-between items-center" style={{ marginBottom:10 }}>
            <span style={{ fontWeight:600, fontSize:'var(--fs-md)' }}><i className="bi bi-person-add" style={{ marginRight:6, color:'#C77700' }}></i>{L('Người đại diện mới', 'New representative')} · <span className="subtle" style={{ fontWeight:500 }}>{cust.shortName || cust.name}</span></span>
            <button className="iconbtn" style={{ width:24, height:24 }} onClick={() => setAddingRep(false)}><i className="bi bi-x-lg" style={{ fontSize:13 }}></i></button>
          </div>
          <div className="col g10" style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <div className="flex g12 wrap">
              <div style={{ flex:'1 1 180px' }}><Field label={t('ct.name')}><input className="input" autoFocus value={nr.name} onChange={e => setNr(s => ({ ...s, name:e.target.value }))} placeholder={L('Họ và tên', 'Full name')} /></Field></div>
              <div style={{ flex:'1 1 180px' }}><Field label={t('ct.title2')}><input className="input" value={nr.title} onChange={e => setNr(s => ({ ...s, title:e.target.value }))} placeholder={L('Chức vụ', 'Job title')} /></Field></div>
            </div>
            <div className="flex g12 wrap">
              <div style={{ flex:'1 1 180px' }}><Field label="Email"><input className="input mono" value={nr.email} onChange={e => setNr(s => ({ ...s, email:e.target.value }))} placeholder="name@company.com" /></Field></div>
              <div style={{ flex:'1 1 180px' }}><Field label={L('Điện thoại', 'Phone')}><input className="input mono" value={nr.phone} onChange={e => setNr(s => ({ ...s, phone:e.target.value }))} placeholder="+84 …" /></Field></div>
            </div>
            <div className="flex g8 justify-end">
              <button className="btn btn-sm" onClick={() => setAddingRep(false)}>{t('c.cancel')}</button>
              <button className="btn btn-sm btn-primary" onClick={saveRep}><i className="bi bi-check-lg"></i>{L('Lưu liên hệ', 'Save contact')}</button>
            </div>
          </div>
        </div>
      )}

      {/* read-only summary line */}
      <div className="flex g16 wrap" style={{ fontSize:'var(--fs-base)', color:'var(--text-muted)', background:'var(--bg-subtle)', padding:'8px 10px', borderRadius:'var(--r-md)' }}>
        <span><b className="muted">{t('cust.mst')}:</b> <span className="mono">{cust.mst || '—'}</span></span>
        <span><b className="muted">{t('hd.address')}:</b> {cust.address || '—'}</span>
        {showEmail && <span><b className="muted">{t('mail.to')}:</b> <span className="mono">{repObj.email || '—'}</span></span>}
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { PartyFields });
